package com.movitech.mobile.cz.base.supplier.bizservice.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.movitech.mobile.cz.base.bizconfig.entity.SSuppliersCategory;
import com.movitech.mobile.cz.base.bizconfig.entity.ext.ExtSSuppliersCategoryTemplate;
import com.movitech.mobile.cz.base.bizconfig.mapper.ext.ExtSSuppliersCategoryTemplateMapper;
import com.movitech.mobile.cz.base.bizconfig.service.SSuppliersCategoryService;
import com.movitech.mobile.cz.base.bizconfig.service.SSuppliersCategoryTemplateService;
import com.movitech.mobile.cz.base.common.aop.ServiceThrowable;
import com.movitech.mobile.cz.base.common.bpm.BpmUtil;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.*;
import com.movitech.mobile.cz.base.common.utils.IdGen;
import com.movitech.mobile.cz.base.modules.config.*;
import com.movitech.mobile.cz.base.modules.config.util.ActionTypeEnumUtil;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.sessionuser.SessionUserVo;
import com.movitech.mobile.cz.base.supplier.bizservice.SSuppliersSubmitOldSysInterfaceService;
import com.movitech.mobile.cz.base.supplier.bizservice.SSuppliersWorkFlowService;
import com.movitech.mobile.cz.base.supplier.bizvo.*;
import com.movitech.mobile.cz.base.supplier.entity.*;
import com.movitech.mobile.cz.base.supplier.entity.ext.ExtSSuppliers;
import com.movitech.mobile.cz.base.supplier.entity.ext.ExtSSuppliersInspectionItems;
import com.movitech.mobile.cz.base.supplier.entity.ext.ExtSSuppliersInspectionTmpl;
import com.movitech.mobile.cz.base.supplier.entity.ext.TransferRequestVO;
import com.movitech.mobile.cz.base.supplier.mapper.ext.ExtSSuppliersMapper;
import com.movitech.mobile.cz.base.supplier.service.*;
import com.movitech.mobile.cz.base.sys.bizvo.AttachmentVO;
import com.movitech.mobile.cz.base.sys.entity.SAttachment;
import com.movitech.mobile.cz.base.sys.entity.SMessages;
import com.movitech.mobile.cz.base.sys.entity.SRegionalCompany;
import com.movitech.mobile.cz.base.sys.entity.SysUser;
import com.movitech.mobile.cz.base.sys.service.SAttachmentService;
import com.movitech.mobile.cz.base.sys.service.SMessagesService;
import com.movitech.mobile.cz.base.sys.service.SRegionalCompanyService;
import com.movitech.mobile.cz.base.sys.service.SysUserService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/3/2.
 */
@Service("sSuppliersWorkFlowService")
@Transactional
public class SSuppliersWorkFlowServiceImpl implements SSuppliersWorkFlowService {

    private static Logger logger = Logger.getLogger(SSuppliersWorkFlowServiceImpl.class);

    @Autowired
    private SSuppliersService sSuppliersService;
    @Autowired
    private SSupplierRcRelateService sSupplierRcRelateService;
    @Autowired
    private SHistoryCommentService sHistoryCommentService;
    @Autowired
    private SMyDealsService sMyDealsService;
    @Autowired
    private SSuppliersCategoryTemplateService sSuppliersCategoryTemplateService;
    @Autowired
    private SSuppliersInspectionScoreService sSuppliersInspectionScoreService;
    @Autowired
    private SSuppliersInspectionService sSuppliersInspectionService;
    @Autowired
    private SMessagesService sMessagesService;
    @Autowired
    private SSuppliersCategoryService sSuppliersCategoryService;

    @Autowired
    @Qualifier("bpmUtil")
    private BpmUtil bpmUtil;
    @Autowired
    private SAttachmentService sAttachmentService;
    @Autowired
    private SCommentConfigService sCommentConfigService;

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SRegionalCompanyService sRegionalCompanyService;
    @Autowired
    private ExtSSuppliersCategoryTemplateMapper extSSuppliersCategoryTemplateMapper;
    @Autowired
    private ExtSSuppliersMapper extSSuppliersMapper;

    @Autowired
    private SSuppliersSubmitOldSysInterfaceService sSuppliersSubmitOldSysInterfaceService;

    @Autowired
    private SSuppliersLastThreeAchieveService sSuppliersLastThreeAchieveService;

    @Autowired
    private SSuppliersInspectionPerformService sSuppliersInspectionPerformService;

    @Autowired
    private SSuppliersInspectionAcService sSuppliersInspectionAcService;
    @Autowired
    private SSuppliersInspectionTmplService sSuppliersInspectionTmplService;
    @Autowired
    private SSuppliersInspectionItemsService sSuppliersInspectionItemsService;

    /**
     * 根据id,更新供方状态
     *
     * @param suppliersAuditRequestVO
     * @return
     */
    @Override
    public boolean updateSupplierStatusNonMBS(SuppliersAuditRequestVO suppliersAuditRequestVO) throws RuntimeException {

        try {
            if (suppliersAuditRequestVO != null) {

                LicenseUtil.INSTANCE.validate();
                SSuppliers sSuppliers = null;
                List<SSupplierRcRelate> supplierRcRelateList = null;
                SSupplierRcRelate sSupplierRcRelateSingle = null;
                if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getId())
                        && StringUtils.isNotEmpty(suppliersAuditRequestVO.getRcRelatedId())) {

                    String userId = UserUtils.getCurrentUserId();
//					SRegionalCompany regionalCompany = sRegionalCompanyService.getRegionalCompanyByMngUser(userId);

                    sSuppliers = sSuppliersService.selectById(suppliersAuditRequestVO.getId());
                    supplierRcRelateList = sSupplierRcRelateService.getSupplierRcRelateBySuppliersId(suppliersAuditRequestVO.getId());
                    sSupplierRcRelateSingle = sSupplierRcRelateService.selectById(suppliersAuditRequestVO.getRcRelatedId());

                    Integer actionType = suppliersAuditRequestVO.getActionType();

                    if (sSuppliers != null && supplierRcRelateList != null && supplierRcRelateList.size() > 0) {

                        Date updateDate = new Date();
                        sSuppliers.setId(suppliersAuditRequestVO.getId());
                        //资质审查
                        boolean batchUpdateFLag = false;
                        for (SSupplierRcRelate sSupplierRcRelate : supplierRcRelateList) {
//	    					sSupplierRcRelate.setRemarks(suppliersAuditRequestVO.getComments());

//	    					sSuppliers.setRemarks(suppliersAuditRequestVO.getComments());

                            if (actionType == ActionTypeEnum.BACK_MODIFY.getCode()) {//退回修改
                                sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.PENDING_MODIFY.getCode()));//待修改
                                sSupplierRcRelate.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());

                                sSuppliers.setRegisterStatus(NumberUtils.toInteger("" + RegisterStatusEnum.PENDING_MODIFY.getCode())); //待修改
                                sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.PENDING_MODIFY.getCode()));//待修改

                                batchUpdateFLag = true;
                            } else if (actionType == ActionTypeEnum.UNPASS_INSPECTION.getCode()) {//审查不通过
                                sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode()));//不合格
                                sSupplierRcRelate.setSupplierBigStatus(SupplierBigStatusEnum.UNQUALIFIED.getCode());//不合格
                                sSupplierRcRelate.setUnqualifiedTime(updateDate);


                                sSuppliers.setRegisterStatus(NumberUtils.toInteger("" + RegisterStatusEnum.UNQUALIFIED.getCode())); //不合格
                                sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode())); //不合格
                                sSuppliers.setUnqualifiedTime(updateDate);

                                batchUpdateFLag = true;
                            } else if (actionType == ActionTypeEnum.PASS_INSPECTION.getCode()) {//审查通过
                                sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.SITE_INSPECTION.getCode()));//现场考察
                                sSupplierRcRelate.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());//潜在

                                sSuppliers.setRegisterStatus(NumberUtils.toInteger("" + RegisterStatusEnum.STORE_APPROVE_ING.getCode())); //入库审批中
                                sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.SITE_INSPECTION.getCode()));  //现场考察

                                batchUpdateFLag = true;
                            }

                        }

                        //现场考察/入库审批
                        boolean singleUpdateFlag = false;

                        if (actionType == ActionTypeEnum.REFUSE_SITE_INSPECTION.getCode()) {//拒绝现场考察申请
                            sSupplierRcRelateSingle.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.SITE_INSPECTION.getCode()));//现场考察
                            sSupplierRcRelateSingle.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());//潜在

                            if (sSuppliers.getIncursionFlag() == CommonConstants.NO_INTEGER) {//非引入
                                sSuppliers.setRegisterStatus(NumberUtils.toInteger("" + RegisterStatusEnum.STORE_APPROVE_ING.getCode())); //入库审批中
                                sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.STORE_APPROVE.getCode())); //入库审批
//                                sSuppliers.setTurnToPotentialTime(updateDate);
                            }

                            singleUpdateFlag = true;
                        } else if (actionType == ActionTypeEnum.SKIP_SITE_INSPECTION.getCode()) {//跳过现场考察
                            sSupplierRcRelateSingle.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.STORE_APPROVE.getCode()));//入库审批
                            sSupplierRcRelateSingle.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());//潜在

                            if (sSuppliers.getIncursionFlag() == CommonConstants.NO_INTEGER) {//非引入
                                sSuppliers.setRegisterStatus(NumberUtils.toInteger("" + RegisterStatusEnum.STORE_APPROVE_ING.getCode())); //入库审批中
                                sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.STORE_APPROVE.getCode())); //入库审批
//                                sSuppliers.setTurnToPotentialTime(updateDate);
                            }

                            singleUpdateFlag = true;
                        } else if (actionType == ActionTypeEnum.APPLY_SITE_INSPECTION.getCode()
                                || actionType == ActionTypeEnum.LEADER_COMMIT.getCode()
                                || actionType == ActionTypeEnum.TEAM_MEMBER_COMMIT.getCode()
                                || actionType == ActionTypeEnum.AGREE_SITE_INSPECTION.getCode()) {//发起现场考察申请\组长打分提交\组员会签提交\同意现场考察申请
                            sSupplierRcRelateSingle.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.SITE_INSPECTION_ING.getCode()));//现场考察中
                            sSupplierRcRelateSingle.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());//潜在

                            if (sSuppliers.getIncursionFlag() == CommonConstants.NO_INTEGER) {//非引入
                                sSuppliers.setRegisterStatus(NumberUtils.toInteger("" + RegisterStatusEnum.STORE_APPROVE_ING.getCode())); //入库审批中
                                sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.SITE_INSPECTION_ING.getCode())); //现场考察中
                            }

                            singleUpdateFlag = true;
                        } else if (actionType == ActionTypeEnum.TURN_TO_PENDING_WATCH.getCode()) { //转为待观察
                            sSupplierRcRelateSingle.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.PENDING_WATCH.getCode()));//待观察
                            sSupplierRcRelateSingle.setSupplierBigStatus(SupplierBigStatusEnum.PENDING_WATCH.getCode());
                            sSupplierRcRelateSingle.setTurnToWatchTime(updateDate);

                            if (sSuppliers.getIncursionFlag() == CommonConstants.NO_INTEGER) {//非引入
                                sSuppliers.setRegisterStatus(NumberUtils.toInteger("" + RegisterStatusEnum.PENDING_WATCH.getCode())); //待观察
                                sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.PENDING_WATCH.getCode())); //待观察
                                sSuppliers.setTurnToWatchTime(updateDate);
                            }

                            singleUpdateFlag = true;
                        } else if (actionType == ActionTypeEnum.UNPASS_SITE_INSPECTION.getCode()) {//考察不通过
                            sSupplierRcRelateSingle.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode()));//不合格
                            sSupplierRcRelateSingle.setSupplierBigStatus(SupplierBigStatusEnum.UNQUALIFIED.getCode());//不合格
                            sSupplierRcRelateSingle.setUnqualifiedTime(updateDate);

                            if (sSuppliers.getIncursionFlag() == CommonConstants.NO_INTEGER
                                    && this.checkIfSetUnQualified(supplierRcRelateList)) {//非引入
                                sSuppliers.setRegisterStatus(NumberUtils.toInteger("" + RegisterStatusEnum.UNQUALIFIED.getCode())); //不合格
                                sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode())); //不合格
                                sSuppliers.setUnqualifiedTime(updateDate);
                            }

                            singleUpdateFlag = true;
                        } else if (actionType == ActionTypeEnum.PASS_SITE_INSPECTION.getCode()) { //考察通过
                            sSupplierRcRelateSingle.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.STORE_APPROVE.getCode())); //入库审批
                            sSupplierRcRelateSingle.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());//潜在

                            if (sSuppliers.getIncursionFlag() == CommonConstants.NO_INTEGER) {//非引入
                                sSuppliers.setRegisterStatus(NumberUtils.toInteger("" + RegisterStatusEnum.STORE_APPROVE_ING.getCode())); //入库审批中
                                sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.STORE_APPROVE.getCode())); //入库审批
                            }

                            singleUpdateFlag = true;
                        } else if (actionType == ActionTypeEnum.LAUNCH_STORE_APPROVE.getCode()) { //发起入库审批
//    						sSupplierRcRelateSingle.setRemarks(suppliersAuditRequestVO.getComments());
                            sSupplierRcRelateSingle.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.STORE_APPROVE_ING.getCode())); //入库审批中
                            sSupplierRcRelateSingle.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());//潜在

                            if (sSuppliers.getIncursionFlag() == CommonConstants.NO_INTEGER) {//非引入
//    							sSuppliers.setRemarks(suppliersAuditRequestVO.getComments());
                                sSuppliers.setRegisterStatus(NumberUtils.toInteger("" + RegisterStatusEnum.STORE_APPROVE_ING.getCode())); //入库审批中
                                sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.STORE_APPROVE_ING.getCode())); //入库审批中
                            }

                            singleUpdateFlag = true;
                        }

                        if (batchUpdateFLag) {
                            sSupplierRcRelateService.updateBatchById(supplierRcRelateList);
                        }

                        if (singleUpdateFlag) {
                            sSupplierRcRelateService.updateById(sSupplierRcRelateSingle);
                        }

                        if (batchUpdateFLag || singleUpdateFlag) {
                            sSuppliersService.updateById(sSuppliers);
                        }


                    }

                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("===============updateSupplierStatusById===e===========:" + e);
            throw new RuntimeException(e.getMessage());
        }

    }

    private boolean checkIfSetUnQualified(List<SSupplierRcRelate> supplierRcRelateList) {

        LicenseUtil.INSTANCE.validate();
        if (supplierRcRelateList != null && supplierRcRelateList.size() > 0) {

            for (SSupplierRcRelate sSupplierRcRelate : supplierRcRelateList) {
                if (sSupplierRcRelate.getSupplierStatus() == NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode())) {
                    continue;
                } else {
                    return false;
                }
            }

            return true;

        }

        return false;
    }

    public boolean updateSupplierStatusByMBS(SuppliersAuditRequestVO suppliersAuditRequestVO, boolean isNew) {

        LicenseUtil.INSTANCE.validate();
        try {
            if (suppliersAuditRequestVO != null) {
                String userId = UserUtils.getCurrentUserId();
                SSuppliers sSuppliers = sSuppliersService.selectById(suppliersAuditRequestVO.getId());
                SSupplierRcRelate sSupplierRcRelate = null;
                boolean isNeedUpdate = false;
                if (sSuppliers.getSupplierBigStatus() != SupplierBigStatusEnum.BLACK_LIBRARY.getCode()) {
                    isNeedUpdate = true;
                    sSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersAuditRequestVO.getRcRelatedId());
                }
                boolean isHasdFirstStored = sSupplierRcRelateService.hasFirstStoredSSupplierRcRelate(suppliersAuditRequestVO.getId());

                Integer actionType = suppliersAuditRequestVO.getActionType();
                Integer abutmentSubType = suppliersAuditRequestVO.getAbutmentSubType(); //对接子类型
                if (actionType == ActionTypeEnum.PASSS_AUDIT.getCode()) {  //审批通过
                    if (AbutmentSubTypeEnum.STORE_APPROVE.getCode() == suppliersAuditRequestVO.getAbutmentSubType()) { //入库审批
                        isNeedUpdate = false;

                        if (!isHasdFirstStored) {
                            sSuppliers.setFirstStoredRegionalCompany(sSupplierRcRelate.getRegionalCompanyId());

                            sSupplierRcRelate.setFirstStoredFlag(CommonConstants.YES_INTEGER);
                            sSupplierRcRelate.setSupplierSource(CommonConstants.SUPPLIER_SOURCE_TYPE_INIT);
                        } else {
                            sSupplierRcRelate.setFirstStoredFlag(CommonConstants.NO_INTEGER);
                            sSupplierRcRelate.setSupplierSource(CommonConstants.SUPPLIER_SOURCE_TYPE_IMPORT);
                        }

                        sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFIED.getCode()));
                        sSupplierRcRelate.setSupplierBigStatus(SupplierBigStatusEnum.QUALIFIED.getCode());
                        sSupplierRcRelate.setStoredTime(new Date());
                        sSupplierRcRelate.setBaseFeilds(userId, "", CommonConstants.DEL_FLAG_NORMAL, false);
                        sSupplierRcRelateService.updateById(sSupplierRcRelate);

                        sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFIED.getCode()));
                        sSuppliers.setSupplierBigStatus(SupplierBigStatusEnum.QUALIFIED.getCode());
                        sSuppliers.setRegisterStatus(NumberUtils.toInteger(RegisterStatusEnum.QUALIFIED.getCode()));
                        if (!isHasdFirstStored) {
                            sSuppliers.setStoredTime(new Date());
                        }
                        sSuppliers.setBaseFeilds(userId, "", CommonConstants.DEL_FLAG_NORMAL, false);
                        String serviceRegionalCompanyIds = sSuppliers.getServiceRegionalCompanyIds();
                        if (StringUtils.isNotEmpty(serviceRegionalCompanyIds)) {
                            serviceRegionalCompanyIds = serviceRegionalCompanyIds + "," + sSupplierRcRelate.getRegionalCompanyId();
                        } else {
                            serviceRegionalCompanyIds = sSupplierRcRelate.getRegionalCompanyId();
                        }
                        if (sSuppliers.getStarLevel() == null || sSuppliers.getStarLevel() == 0) {
                            sSuppliers.setStarLevel(2);
                        }
                        sSuppliers.setServiceRegionalCompanyIds(serviceRegionalCompanyIds);
                        sSuppliersService.updateById(sSuppliers);

                        //审批通知
                        SMessages message = new SMessages();
                        message.setMsgType(MessagesMsgTypeEnum.ANNOUNCEMENT_NOTICE.getCode());
                        message.setMsgTitle(sCommentConfigService.getValueByCode(CommentConfigEnum.STORE_APPROVE_PASS.getCode())
                                .replace("{0}", sRegionalCompanyService.getRegionalCompanyNames(new String[]{sSupplierRcRelate.getRegionalCompanyId()})));
//                        message.setMsgContent(suppliersAuditRequestVO.getComments());
                        message.setUserIds(sSuppliers.getSysUserId());
                        message.setFlowFormId(sSuppliers.getId());
                        sMessagesService.addSMessages(message);

                        //同步供应商数据到旧系统
//                        sSuppliersSubmitOldSysInterfaceService.abutmentSuplierData(sSuppliers, true);
                        sSuppliersSubmitOldSysInterfaceService.abutmentSuplierData2MDM(sSuppliers, true);

                    } else if (AbutmentSubTypeEnum.TURN_TO_PENDING_WATCH_APPROVE.getCode() == abutmentSubType) {//转待观察通过
                        sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.PENDING_WATCH.getCode())); //待观察
                        sSupplierRcRelate.setSupplierBigStatus(SupplierBigStatusEnum.PENDING_WATCH.getCode());
                    } else if (AbutmentSubTypeEnum.TURN_TO_UNQUALIFIED_APPROVE.getCode() == abutmentSubType) {//转不合格审批通过
                        sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode())); //不合格
                        sSupplierRcRelate.setSupplierBigStatus(SupplierBigStatusEnum.UNQUALIFIED.getCode());
                    } else if (AbutmentSubTypeEnum.TURN_TO_POTENTIAL_APPROVE.getCode() == abutmentSubType) {//转潜在审批通过
                        if (sSuppliers.getSupplierBigStatus() == SupplierBigStatusEnum.BLACK_LIBRARY.getCode()) {//黑库转潜在
                            isNeedUpdate = false;
                            sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFICATION_INSPECTION.getCode()));
                            sSuppliers.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());
                            sSuppliers.setRegisterStatus(Integer.valueOf(RegisterStatusEnum.PENDING_WATCH.getCode()));
                            sSuppliersService.updateById(sSuppliers);
                            List<SSupplierRcRelate> supplierRcRelateList = sSupplierRcRelateService.getSupplierRcRelateBySuppliersId(suppliersAuditRequestVO.getId());
                            for (SSupplierRcRelate obj : supplierRcRelateList) {
                                obj.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFICATION_INSPECTION.getCode()));
                                obj.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());
                            }
                            sSupplierRcRelateService.updateBatchById(supplierRcRelateList);
                        } else {
                            sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFICATION_INSPECTION.getCode())); //潜在
                            sSupplierRcRelate.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());
                        }
                    } else if (AbutmentSubTypeEnum.TURN_TO_BLACK_LIBRARY_APPROVE.getCode() == abutmentSubType) {//转黑库审批通过
                        isNeedUpdate = false;
                        sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.BLACK_LIBRARYS.getCode()));
                        sSuppliers.setSupplierBigStatus(SupplierBigStatusEnum.BLACK_LIBRARY.getCode());
                        sSuppliers.setRegisterStatus(Integer.valueOf(RegisterStatusEnum.BLACKLIST.getCode()));
                        sSuppliersService.updateById(sSuppliers);
                        List<SSupplierRcRelate> supplierRcRelateList = sSupplierRcRelateService.getSupplierRcRelateBySuppliersId(suppliersAuditRequestVO.getId());
                        for (SSupplierRcRelate obj : supplierRcRelateList) {
                            obj.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.BLACK_LIBRARYS.getCode()));
                            obj.setSupplierBigStatus(SupplierBigStatusEnum.BLACK_LIBRARY.getCode());
                        }
                        sSupplierRcRelateService.updateBatchById(supplierRcRelateList);
                    }
                } else if (actionType == ActionTypeEnum.UNPASS_AUDIT.getCode()) {//审批不通过
                    if (AbutmentSubTypeEnum.STORE_APPROVE.getCode() == suppliersAuditRequestVO.getAbutmentSubType()) { //入库审批
                        isNeedUpdate = false;
                        sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.STORE_APPROVE.getCode()));
                        sSupplierRcRelate.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());
                        sSupplierRcRelateService.updateById(sSupplierRcRelate);
//                        List<SSupplierRcRelate> supplierRcRelateList = sSupplierRcRelateService.getSupplierRcRelateBySuppliersId(suppliersAuditRequestVO.getId());
//                        boolean isUNQUALIFIED=true;//是否子表全是不合格
//                        for(SSupplierRcRelate obj:supplierRcRelateList){
//                            if(obj.getSupplierStatus()!=null&&obj.getSupplierStatus()!=NumberUtils.toInteger(""+SupplierStatusEnum.UNQUALIFIED.getCode())){
//                                isUNQUALIFIED=false;
//                            }
//                        }
//                        if(isUNQUALIFIED){
//                            sSuppliers.setSupplierStatus(NumberUtils.toInteger(""+SupplierStatusEnum.UNQUALIFIED.getCode()));
//                            sSuppliers.setSupplierBigStatus(SupplierBigStatusEnum.UNQUALIFIED.getCode());
//                            sSuppliers.setRegisterStatus(Integer.valueOf(RegisterStatusEnum.UNQUALIFIED.getCode()));
//                            sSuppliers.setUnqualifiedTime(new Date());
//                            sSuppliersService.updateById(sSuppliers);
//                        }

                        //审批通知
                        SMessages message = new SMessages();
                        message.setMsgType(MessagesMsgTypeEnum.ANNOUNCEMENT_NOTICE.getCode());
                        message.setMsgTitle(sCommentConfigService.getValueByCode(CommentConfigEnum.STORE_APPROVE_UNPASS.getCode())
                                .replace("{0}", sRegionalCompanyService.getRegionalCompanyNames(new String[]{sSupplierRcRelate.getRegionalCompanyId()})));
//                        message.setMsgContent(suppliersAuditRequestVO.getComments());
                        message.setUserIds(sSuppliers.getSysUserId());
                        message.setFlowFormId(sSuppliers.getId());
                        sMessagesService.addSMessages(message);
                    } else if (AbutmentSubTypeEnum.TURN_TO_PENDING_WATCH_APPROVE.getCode() == abutmentSubType) {//转待观察审批不通过
                        sSupplierRcRelate.setTurnToWatchTime(null);
                        sSupplierRcRelate.setTurnToWatchDesc(null);
                        if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.QUALIFIED.getCode()) {
                            sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFIED.getCode())); //合格
                        } else if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.UNQUALIFIED.getCode()) {
                            sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode())); //不合格
                        }
                    } else if (AbutmentSubTypeEnum.TURN_TO_UNQUALIFIED_APPROVE.getCode() == abutmentSubType) {//转不合格审批不通过
                        sSupplierRcRelate.setUnqualifiedTime(null);
                        sSupplierRcRelate.setTurnToUnqualifiedDesc(null);
                        if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.QUALIFIED.getCode()) {
                            sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFIED.getCode())); //合格
                        } else if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.UNQUALIFIED.getCode()) {
                            sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode())); //不合格
                        }
                    } else if (AbutmentSubTypeEnum.TURN_TO_POTENTIAL_APPROVE.getCode() == abutmentSubType) {//转潜在审批不通过
                        if (sSuppliers.getSupplierBigStatus() == SupplierBigStatusEnum.BLACK_LIBRARY.getCode()) {//黑库转潜在
                            isNeedUpdate = false;
                            sSuppliers.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.BLACK_LIBRARYS.getCode()));
                            sSuppliers.setSupplierBigStatus(SupplierBigStatusEnum.BLACK_LIBRARY.getCode());
                            sSuppliers.setRegisterStatus(Integer.valueOf(RegisterStatusEnum.BLACKLIST.getCode()));
                            sSuppliers.setTurnToPotentialDesc(null);
                            sSuppliers.setTurnToPotentialTime(null);
                            sSuppliersService.updateById(sSuppliers);
                            List<SSupplierRcRelate> supplierRcRelateList = sSupplierRcRelateService.getSupplierRcRelateBySuppliersId(suppliersAuditRequestVO.getId());
                            for (SSupplierRcRelate obj : supplierRcRelateList) {
                                obj.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.BLACK_LIBRARYS.getCode()));
                                obj.setSupplierBigStatus(SupplierBigStatusEnum.BLACK_LIBRARY.getCode());
                                obj.setTurnToPotentialDesc(null);
                                obj.setTurnToPotentialTime(null);
                            }
                            sSupplierRcRelateService.updateBatchById(supplierRcRelateList);
                        } else {//不合格转潜在
                            sSupplierRcRelate.setTurnToPotentialTime(null);
                            sSupplierRcRelate.setTurnToPotentialDesc(null);
                            sSupplierRcRelate.setSupplierStatus(Integer.valueOf(SupplierStatusEnum.UNQUALIFIED.getCode()));
                            if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.QUALIFIED.getCode()) {
                                sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFIED.getCode())); //合格
                            } else if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.UNQUALIFIED.getCode()) {
                                sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode())); //不合格
                            }
                        }
                    } else if (AbutmentSubTypeEnum.TURN_TO_BLACK_LIBRARY_APPROVE.getCode() == abutmentSubType) {//转黑库审批不通过
                        isNeedUpdate = false;
                        int supplierStatus = NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode());
                        SSupplierRcRelate oriSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersAuditRequestVO.getRcRelatedId());//流程发起地区公司
                        if (oriSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.QUALIFIED.getCode()) {
                            oriSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFIED.getCode()));
                            supplierStatus = supplierStatus = NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFIED.getCode());
                        } else {//不合格转黑库被驳回的情况
                            oriSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.UNQUALIFIED.getCode()));

                            List<SSupplierRcRelate> supplierRcRelateList = sSupplierRcRelateService.getSupplierRcRelateBySuppliersId(suppliersAuditRequestVO.getId());
                            for (SSupplierRcRelate obj : supplierRcRelateList) {
                                if (obj.getSupplierBigStatus() == SupplierBigStatusEnum.QUALIFIED.getCode()) {
                                    //obj.setSupplierStatus(NumberUtils.toInteger(""+SupplierStatusEnum.QUALIFIED.getCode()));
                                    supplierStatus = NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFIED.getCode());
                                    break;
                                }
                            }
                        }
                        sSupplierRcRelateService.updateById(oriSupplierRcRelate);

                        //
                        sSuppliers.setSupplierStatus(supplierStatus);
                        sSuppliersService.updateById(sSuppliers);
                    }
                }
                if (isNeedUpdate) {
                    sSupplierRcRelateService.updateById(sSupplierRcRelate);
                }

            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("===============updateSupplierStatus===e===========:" + e);
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 根据供方id,获取供放基本信息
     *
     * @param id
     * @return
     */
    @Override
    public SuppliersSiteInspectionResponseVO getSuppliersInspectionBaseDetails(String id) {
        return null;
    }

    /**
     * 资质考察是否已处理
     *
     * @param relatedId
     * @param rcRelatedId
     * @return
     */
    private String checkQualificationInspectionIfDealCompleted(String relatedId, String rcRelatedId) {

        LicenseUtil.INSTANCE.validate();
        SMyDeals param = new SMyDeals();
        param.setDealType(DealTypeEnum.SUPPLIERS.getCode());
        param.setDealSubType(MyDealSubTypeEnum.QUALIFICATION_INSPECTION.getCode());
        param.setRelatedId(relatedId);
        param.setSubRelatedId(rcRelatedId);
        param.setDelFlag(CommonConstants.NO_INTEGER);

        SMyDeals sMyDeals = sMyDealsService.selectOneByEntity(param);
        if (sMyDeals != null) {

            if (CommonConstants.DONG_FLAG == sMyDeals.getDoneFlag()) {
                SRegionalCompany rc = sRegionalCompanyService.getRegionalCompanyByMngUser(sMyDeals.getUpdateBy());
                SysUser user = sysUserService.selectById(sMyDeals.getUpdateBy());
                if (rc != null && user != null) {
                    return rc.getRegionalCompanyName() + user.getName() + "已经做了资质审查处理";
                } else {
                    return "已处理资质审查的地区公司或者用户信息出错了";
                }

            }

            return null;

        } else {

            return "数据错误，未发现待办";

        }

    }

    /**
     * 供方资质审查流程
     *
     * @param suppliersAuditRequestVO
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> qualificationInspection(SuppliersAuditRequestVO suppliersAuditRequestVO) throws RuntimeException {

        LicenseUtil.INSTANCE.validate();
        RestReturnResult<Object> restReturnResult = RestReturnResult.error();
        try {
//        	String checkMsg = this.checkQualificationInspectionIfDealCompleted(suppliersAuditRequestVO.getId(), suppliersAuditRequestVO.getRcRelatedId());
//        	if(checkMsg != null){
//        		throw new RuntimeException(checkMsg, new ServiceThrowable());
//        	}
            //supplierRcRelateList = sSupplierRcRelateService.getSupplierRcRelateBySuppliersId(suppliersAuditRequestVO.getId());

            SSupplierRcRelate sSupplierRcRelateSingle = sSupplierRcRelateService.selectById(suppliersAuditRequestVO.getRcRelatedId());
            if (!SupplierStatusEnum.QUALIFICATION_INSPECTION.getCode().equals(String.valueOf(sSupplierRcRelateSingle.getSupplierStatus()))) {
                throw new RuntimeException("当前已过资质审查！", new ServiceThrowable());
            }

            //Step1: 供应商基本情况及地区公司关联表相关状态变更
            this.updateSupplierStatusNonMBS(suppliersAuditRequestVO);

            //Step2: 审批历史记录更新
            SHistoryComment sHistoryComment = new SHistoryComment();

            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
            sHistoryComment.setRelatedId(suppliersAuditRequestVO.getId());
            sHistoryComment.setSubRelatedId(suppliersAuditRequestVO.getRcRelatedId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.QUALIFICATION_INSPECTION_NODE_NAME.getCode()));
            sHistoryComment.setCommentContent(suppliersAuditRequestVO.getComments());


            //Step 3: 添加待办已办记录
            SSuppliers sSuppliers = sSuppliersService.selectById(suppliersAuditRequestVO.getId());
            String userId = UserUtils.getCurrentUserId();

            String titleTemplate = sCommentConfigService.getValueByCode(CommentConfigEnum.MY_DEAL_TEMPLATE.getCode());
            String title = MessageFormat.format(titleTemplate, MyDealSubTypeEnum.SITE_INSPECTION.getDesc(), sSuppliers.getCompanyName()/* + MyDealSubTypeEnum.SITE_INSPECTION.getDesc()*/);

            SMessages sMessage = new SMessages();
            sMessage.setUserIds(sSuppliers.getSysUserId());
            sMessage.setMsgType(MessagesMsgTypeEnum.ANNOUNCEMENT_NOTICE.getCode());
            sMessage.setMsgContent(suppliersAuditRequestVO.getComments());

            int actionType = suppliersAuditRequestVO.getActionType();
            if (actionType == ActionTypeEnum.BACK_MODIFY.getCode()) {//退回修改
                sHistoryComment.setActionName(ActionTypeEnum.BACK_MODIFY.getDesc());
                sHistoryComment.setAgreeFlag(CommonConstants.NO_AGREE_FLAG);
                sMessage.setFlowFormId(suppliersAuditRequestVO.getRcRelatedId());
                SCommentConfig sCommentConfig = sCommentConfigService.getByCode(CommentConfigEnum.QUALIFICATION_INSPECTION_UNPASS.getCode());
                sMessage.setMsgTitle(sCommentConfig.getConfigValue());
                sMessage.setJumpFlag(sCommentConfig.getJumpFlag());
                sMessagesService.addSMessages(sMessage);

                //更新已办：资质审查,批量更新所有已办
                sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), null, DealTypeEnum.SUPPLIERS.getCode(),
                        null, 0, 0, null, null, true, null);

            } else if (actionType == ActionTypeEnum.UNPASS_INSPECTION.getCode()) {//审查不通过
                sHistoryComment.setActionName(ActionTypeEnum.UNPASS_INSPECTION.getDesc());
                sHistoryComment.setAgreeFlag(CommonConstants.NO_AGREE_FLAG);

                SCommentConfig sCommentConfig = sCommentConfigService.getByCode(CommentConfigEnum.QUALIFICATION_INSPECTION_UNQUALIFIED.getCode());
                sMessage.setMsgTitle(sCommentConfig.getConfigValue());
                sMessage.setJumpFlag(sCommentConfig.getJumpFlag());
                sMessage.setFlowFormId(suppliersAuditRequestVO.getRcRelatedId());
                sMessagesService.addSMessages(sMessage);

                //更新已办：资质审查,批量更新所有已办
                sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), null, DealTypeEnum.SUPPLIERS.getCode(),
                        null, 0, 0, null, null, true, null);

            } else if (actionType == ActionTypeEnum.PASS_INSPECTION.getCode()) {//审查通过
                sHistoryComment.setActionName(ActionTypeEnum.PASS_INSPECTION.getDesc());
                sHistoryComment.setAgreeFlag(CommonConstants.AGREE_FLAG);

                //资质审查，批量更新所有已办,新增当前意向地区公司待办
                sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), suppliersAuditRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(),
                        new String[]{userId}, MyDealSubTypeEnum.SITE_INSPECTION.getCode(), MyDealActionTypeEnum.SITE_INSPECTION.getCode(),
                        title, userId, true, null);

                //更新actionType
                SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersAuditRequestVO.getRcRelatedId());
                if (sSupplierRcRelate != null) {
                    sSupplierRcRelate.setActionType(MyDealActionTypeEnum.SITE_INSPECTION.getCode());

                    sSupplierRcRelateService.updateById(sSupplierRcRelate);
                }
            }

            sHistoryCommentService.saveSHistoryComment(sHistoryComment);


            restReturnResult = restReturnResult.success();

            return restReturnResult;

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("===============qualificationInspection===e===========:" + e);
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }


    /**
     * 判断现场考察是否需要走流程
     *
     * @param rcRelatedId
     * @return
     */
    private boolean checkSiteInspectionByWorkflow(String rcRelatedId) {

        SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(rcRelatedId);

        if (sSupplierRcRelate != null
                && NumberUtils.toInteger("" + SupplierStatusEnum.QUALIFIED.getCode()) == sSupplierRcRelate.getSupplierStatus()) {
            return false;
        }

        return true;
    }

    @Override
    public String addSuppliersInspection(SuppliersInspectionRequestVO suppliersInspectionRequestVO) {
        try {
            LicenseUtil.INSTANCE.validate();
            SSuppliersInspection sSuppliersInspection = new SSuppliersInspection();
            String sSuppliersInspectionId = IdGenUtils.uuid();
            sSuppliersInspection.setId(sSuppliersInspectionId);
            sSuppliersInspection.setSuppliersId(suppliersInspectionRequestVO.getSuppliersId());
            sSuppliersInspection.setInspectionTemplateId(suppliersInspectionRequestVO.getInspectionTemplateId());
            sSuppliersInspection.setInspectionTemplateName(suppliersInspectionRequestVO.getInspectionTemplateName());
            sSuppliersInspection.setInspectionGroupUserIds(suppliersInspectionRequestVO.getInspectionGroupUserIds());
            sSuppliersInspection.setInspectionLeaderUserId(suppliersInspectionRequestVO.getInspectionLeaderUserId());
            sSuppliersInspection.setInspectionMemberUserIds(suppliersInspectionRequestVO.getInspectionMemberUserIds());
            sSuppliersInspection.setRegionalCompanyId(suppliersInspectionRequestVO.getRegionalCompanyId());
            sSuppliersInspection.setDoneFlag(CommonConstants.DONG_FLAG);
            sSuppliersInspection.setGroupUserDoneFlag(CommonConstants.UNDONG_FLAG);
            sSuppliersInspection.setLeaderDoneFlag(CommonConstants.UNDONG_FLAG);
            sSuppliersInspection.setCountSignDoneFlag(CommonConstants.UNDONG_FLAG);
            sSuppliersInspection.setInspectionProjects(suppliersInspectionRequestVO.getInspectionProjects());
            sSuppliersInspection.setSupplierCategoryIds(suppliersInspectionRequestVO.getIntentionSupplierCategoryIds());
            sSuppliersInspection.setInspectionType(2);
            sSuppliersInspection.setInspectionSuggestion(suppliersInspectionRequestVO.getInspectionSuggestion());
            sSuppliersInspection.setCreateDate(suppliersInspectionRequestVO.getCreateDate());
            sSuppliersInspection.setUpdateDate(suppliersInspectionRequestVO.getCreateDate());
            sSuppliersInspectionService.addSSuppliersInspection(sSuppliersInspection);

            List<AttachmentVO> attachmentVOList = suppliersInspectionRequestVO.getLstAttachments();
            if (attachmentVOList != null && attachmentVOList.size() > 0) {
                List<SAttachment> attachmentList = new ArrayList<SAttachment>();
                attachmentList = ListObjCopyUtil.copyTo(attachmentVOList, SAttachment.class);
                for (SAttachment sAttachment : attachmentList) {
                    sAttachment.setRelatedId(sSuppliersInspectionId);
                    sAttachment.setFormId(suppliersInspectionRequestVO.getSuppliersId());
                    sAttachment.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
                }
                sAttachmentService.insertBatch(attachmentList);
            }
            return sSuppliersInspectionId;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }


    @Override
    public void updateSupplierInspectionAttach(SuppliersInspectionRequestVO suppliersInspectionRequestVO) {
        try {
            LicenseUtil.INSTANCE.validate();
            SAttachment sAttachment = new SAttachment();
            sAttachment.setDelFlag(CommonConstants.DEL_FLAG_DELETE);
            EntityWrapper entityWrapper = new EntityWrapper();
            SAttachment where = new SAttachment();
            entityWrapper.setEntity(where);
            where.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_13.getCode());
            where.setRelatedId(suppliersInspectionRequestVO.getId());
            sAttachmentService.update(sAttachment, entityWrapper);

            List<AttachmentVO> attachmentVOList = suppliersInspectionRequestVO.getLstAttachments();
            if (attachmentVOList != null && attachmentVOList.size() > 0) {
                List<SAttachment> attachmentList = new ArrayList<SAttachment>();
                attachmentList = ListObjCopyUtil.copyTo(attachmentVOList, SAttachment.class);
                for (SAttachment sAttachment1 : attachmentList) {
                    sAttachment1.setId(null);
                    sAttachment1.setRelatedId(suppliersInspectionRequestVO.getId());
                    sAttachment1.setFormId(suppliersInspectionRequestVO.getSuppliersId());
                    sAttachment1.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
                }
                sAttachmentService.insertBatch(attachmentList);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }

    @Override
    public void deleteSupplierInspectionById(String id) {
        SSuppliersInspection sSuppliersInspection = new SSuppliersInspection();
        sSuppliersInspection.setId(id);
        sSuppliersInspection.setDelFlag(CommonConstants.DEL_FLAG_DELETE);
        sSuppliersInspectionService.updateById(sSuppliersInspection);
    }

    /**
     * 现场考察
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> doSuppliersInspection(SuppliersInspectionRequestVO suppliersInspectionRequestVO) throws RuntimeException {
        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        try {

            LicenseUtil.INSTANCE.validate();
            String userId = UserUtils.getCurrentUserId();
            int actionType = suppliersInspectionRequestVO.getActionType();
            boolean workflowFlag = this.checkSiteInspectionByWorkflow(suppliersInspectionRequestVO.getRcRelatedId());

            //考察公告id
            String thirdRelatedId = null;

            if (actionType == ActionTypeEnum.APPLY_SITE_INSPECTION.getCode()) {//发起现场考察申请

                if (StringUtils.isBlank(suppliersInspectionRequestVO.getId())) {
                    //考察报告
                    SSuppliersInspection sSuppliersInspection = new SSuppliersInspection();
                    String sSuppliersInspectionId = IdGenUtils.uuid();
                    sSuppliersInspection.setId(sSuppliersInspectionId);
                    sSuppliersInspection.setSuppliersId(suppliersInspectionRequestVO.getSuppliersId());
                    sSuppliersInspection.setInspectionTemplateId(suppliersInspectionRequestVO.getInspectionTemplateId());
                    sSuppliersInspection.setInspectionTemplateName(suppliersInspectionRequestVO.getInspectionTemplateName());
                    sSuppliersInspection.setInspectionGroupUserIds(suppliersInspectionRequestVO.getInspectionGroupUserIds());
                    sSuppliersInspection.setInspectionLeaderUserId(suppliersInspectionRequestVO.getInspectionLeaderUserId());
                    sSuppliersInspection.setInspectionMemberUserIds(suppliersInspectionRequestVO.getInspectionMemberUserIds());
                    sSuppliersInspection.setInspectionTime(suppliersInspectionRequestVO.getInspectionTime());
                    sSuppliersInspection.setRegionalCompanyId(suppliersInspectionRequestVO.getRegionalCompanyId());
                    sSuppliersInspection.setInspectionAnnounceUserIds(suppliersInspectionRequestVO.getInspectionAnnounceUserIds());
                    sSuppliersInspection.setDoneFlag(CommonConstants.UNDONG_FLAG);
                    sSuppliersInspection.setGroupUserDoneFlag(CommonConstants.UNDONG_FLAG);
                    sSuppliersInspection.setLeaderDoneFlag(CommonConstants.UNDONG_FLAG);
                    sSuppliersInspection.setCountSignDoneFlag(CommonConstants.UNDONG_FLAG);
                    sSuppliersInspection.setInspectionProjects(suppliersInspectionRequestVO.getInspectionProjects());
                    sSuppliersInspection.setSupplierCategoryIds(suppliersInspectionRequestVO.getIntentionSupplierCategoryIds());
                    sSuppliersInspectionService.addSSuppliersInspection(sSuppliersInspection);

                    //考察公告
                    SMessages sMessages = new SMessages();
                    thirdRelatedId = IdGenUtils.uuid();
                    sMessages.setId(thirdRelatedId);
                    sMessages.setMsgType(MessagesMsgTypeEnum.MsgType6.getCode()); //现场考察公告
                    sMessages.setMsgTitle(suppliersInspectionRequestVO.getAnnouncementName());
                    sMessages.setMsgContent(suppliersInspectionRequestVO.getAnnouncementContent());
                    sMessages.setSubRelatedId(sSuppliersInspectionId);
                    sMessages.setShowFlag(CommonConstants.NO_INTEGER);
                    sMessagesService.addSMessages(sMessages);

                    SSuppliers sSuppliers = sSuppliersService.selectById(suppliersInspectionRequestVO.getSuppliersId());
                    //添加模版
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("categoryId", sSuppliers.getSupplierServiceCategoryIds());
                    params.put("templateType", CommonConstants.TEMPLATE_CATEGORY_1);

                    List<ExtSSuppliersCategoryTemplate> list = extSSuppliersCategoryTemplateMapper.getSuppliersCategoryTemplateByCategoryAndType(params);
                    for (ExtSSuppliersCategoryTemplate extSSuppliersCategoryTemplate : list) {
                        //SSuppliersCategoryTemplate sSuppliersCategoryTemplate = sSuppliersCategoryTemplateService.selectById(suppliersInspectionRequestVO.getInspectionTemplateId());
                        SSuppliersInspectionScore sSuppliersInspectionScore = new SSuppliersInspectionScore();
                        sSuppliersInspectionScore.setSuppliersId(suppliersInspectionRequestVO.getSuppliersId());
                        sSuppliersInspectionScore.setSuppliersInspectionId(sSuppliersInspectionId);
                        sSuppliersInspectionScore.setEvaluationDimension(extSSuppliersCategoryTemplate.getEvaluationDimension());
                        sSuppliersInspectionScore.setEvaluationIndicator(extSSuppliersCategoryTemplate.getEvaluationIndicator());
                        sSuppliersInspectionScore.setScoreStandard(extSSuppliersCategoryTemplate.getScoreStandard());
//                        if(extSSuppliersCategoryTemplate.getScores()!=null) sSuppliersInspectionScore.setScores(Double.valueOf(extSSuppliersCategoryTemplate.getScores()));
                        sSuppliersInspectionScoreService.addSSuppliersInspectionScore(sSuppliersInspectionScore);
                    }
                } else {
                    //考察报告
                    SSuppliersInspection sSuppliersInspectionDB = sSuppliersInspectionService.selectById(suppliersInspectionRequestVO.getId());
                    if (sSuppliersInspectionDB != null) {
                        sSuppliersInspectionDB.setSuppliersId(suppliersInspectionRequestVO.getSuppliersId());
                        sSuppliersInspectionDB.setInspectionTemplateId(suppliersInspectionRequestVO.getInspectionTemplateId());
                        sSuppliersInspectionDB.setInspectionTemplateName(suppliersInspectionRequestVO.getInspectionTemplateName());
                        sSuppliersInspectionDB.setInspectionGroupUserIds(suppliersInspectionRequestVO.getInspectionGroupUserIds());
                        sSuppliersInspectionDB.setInspectionLeaderUserId(suppliersInspectionRequestVO.getInspectionLeaderUserId());
                        sSuppliersInspectionDB.setInspectionMemberUserIds(suppliersInspectionRequestVO.getInspectionMemberUserIds());
                        sSuppliersInspectionDB.setInspectionAnnounceUserIds(suppliersInspectionRequestVO.getInspectionAnnounceUserIds());
                        sSuppliersInspectionDB.setInspectionTime(suppliersInspectionRequestVO.getInspectionTime());
                        sSuppliersInspectionDB.setRegionalCompanyId(suppliersInspectionRequestVO.getRegionalCompanyId());
                        sSuppliersInspectionDB.setDoneFlag(CommonConstants.UNDONG_FLAG);
                        sSuppliersInspectionDB.setGroupUserDoneFlag(CommonConstants.UNDONG_FLAG);
                        sSuppliersInspectionDB.setLeaderDoneFlag(CommonConstants.UNDONG_FLAG);
                        sSuppliersInspectionDB.setCountSignDoneFlag(CommonConstants.UNDONG_FLAG);
                        sSuppliersInspectionDB.setInspectionProjects(suppliersInspectionRequestVO.getInspectionProjects());
                        sSuppliersInspectionDB.setSupplierCategoryIds(suppliersInspectionRequestVO.getIntentionSupplierCategoryIds());
                        sSuppliersInspectionDB.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);
                        sSuppliersInspectionService.updateById(sSuppliersInspectionDB);
                    }


                    //考察公告
                    EntityWrapper wrapper = new EntityWrapper();
                    SMessages param = new SMessages();
                    param.setMsgType(MessagesMsgTypeEnum.MsgType6.getCode()); //现场考察公告
                    param.setSubRelatedId(suppliersInspectionRequestVO.getId());
                    //param.setShowFlag(CommonConstants.NO_INTEGER);
                    param.setDelFlag(CommonConstants.NO_INTEGER);
                    wrapper.setEntity(param);
                    SMessages sMessagesDB = sMessagesService.selectOne(wrapper);

                    if (sMessagesDB != null) {
                        thirdRelatedId = sMessagesDB.getId();
                        sMessagesDB.setMsgTitle(suppliersInspectionRequestVO.getAnnouncementName());
                        sMessagesDB.setMsgContent(suppliersInspectionRequestVO.getAnnouncementContent());
                        sMessagesDB.setShowFlag(CommonConstants.NO_INTEGER);
                        sMessagesDB.setUserIds(suppliersInspectionRequestVO.getInspectionGroupUserIds());
                        sMessagesService.updateById(sMessagesDB);
                    }

                }

            }


            //供应商基本情况及地区公司关联表相关状态变更
            SuppliersAuditRequestVO suppliersAuditRequestVO = new SuppliersAuditRequestVO();
            suppliersAuditRequestVO.setId(suppliersInspectionRequestVO.getSuppliersId());
            suppliersAuditRequestVO.setRcRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
            suppliersAuditRequestVO.setActionType(suppliersInspectionRequestVO.getActionType());

            if (workflowFlag) {
                this.updateSupplierStatusNonMBS(suppliersAuditRequestVO);
            }

            //Step2: 审批历史记录更新
            SHistoryComment sHistoryComment = new SHistoryComment();

            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
            sHistoryComment.setRelatedId(suppliersInspectionRequestVO.getSuppliersId());
            sHistoryComment.setSubRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.SITE_INSPECTION_NODE_NAME.getCode()));
            //sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.SITE_INSPECTION_COMMENT_CONTENT.getCode()));

            //Action: 4：跳过现场考察，5：发起现场考察申请
            sHistoryComment.setActionName(ActionTypeEnumUtil.actionTypeEnumMap.get(suppliersInspectionRequestVO.getActionType()));
            sHistoryComment.setAgreeFlag(CommonConstants.AGREE_FLAG);

            sHistoryCommentService.saveSHistoryComment(sHistoryComment);

            //Step 3: 添加待办已办记录

            SSuppliers sSuppliers = sSuppliersService.selectById(suppliersInspectionRequestVO.getSuppliersId());

            String titleTemplate = sCommentConfigService.getValueByCode(CommentConfigEnum.MY_DEAL_TEMPLATE.getCode());
            String title = "";

            if (suppliersInspectionRequestVO.getActionType() == ActionTypeEnum.SKIP_SITE_INSPECTION.getCode()) {

                if (sSuppliers != null) {
                    title = MessageFormat.format(titleTemplate, MyDealSubTypeEnum.STORE_APPOVE.getDesc(), sSuppliers.getCompanyName()/* + MyDealSubTypeEnum.SITE_INSPECTION.getDesc()*/);
                }

                SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersInspectionRequestVO.getRcRelatedId());
                //更新意向供方分类类别
                String supplierCategoryActualIds = null;
                if (sSupplierRcRelate != null) {
                    if (StringUtils.isNotBlank(sSupplierRcRelate.getSupplierCategoryActualIds())) {
                        supplierCategoryActualIds = sSupplierRcRelate.getSupplierCategoryActualIds() + "," + suppliersInspectionRequestVO.getIntentionSupplierCategoryIds();
                    } else {
                        supplierCategoryActualIds = suppliersInspectionRequestVO.getIntentionSupplierCategoryIds();
                    }
                    sSupplierRcRelate.setSupplierCategoryActualIds(supplierCategoryActualIds);
                    sSupplierRcRelate.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);

                    sSupplierRcRelateService.updateById(sSupplierRcRelate);
                }

                //考察报告更新;
                if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getReportId())) {
                    SSuppliersInspection sSuppliersInspection = sSuppliersInspectionService.selectById(suppliersAuditRequestVO.getReportId());

                    if (sSuppliersInspection != null) {
                        if (StringUtils.isNotBlank(suppliersInspectionRequestVO.getIntentionSupplierCategoryIds())) {
                            sSuppliersInspection.setSupplierCategoryActualIds(suppliersInspectionRequestVO.getIntentionSupplierCategoryIds());
                        }
                        sSuppliersInspection.setDoneFlag(CommonConstants.YES_INTEGER);
                        sSuppliersInspection.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);

                        sSuppliersInspectionService.updateById(sSuppliersInspection);
                    }

                }

                if (workflowFlag) {
                    sMyDealsService.dealMyDeals(suppliersInspectionRequestVO.getSuppliersId(), suppliersInspectionRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(), new String[]{userId},
                            MyDealSubTypeEnum.STORE_APPOVE.getCode(), MyDealActionTypeEnum.STORE_APPOVE.getCode(),
                            title, userId, true, null);
                } else {
                    sMyDealsService.dealMyDeals(suppliersInspectionRequestVO.getSuppliersId(), suppliersInspectionRequestVO.getRcRelatedId(),
                            0, null, 0, 0, null, userId, true, null);
                }

            } else if (suppliersInspectionRequestVO.getActionType() == ActionTypeEnum.APPLY_SITE_INSPECTION.getCode()) {

                //申请执行现场考察
                if (sSuppliers != null) {
                    title = MessageFormat.format(titleTemplate, MyDealSubTypeEnum.SITE_INSPECTION.getDesc(), sSuppliers.getCompanyName() + sCommentConfigService.getValueByCode(CommentConfigEnum.SITE_INSPECTION_APPLY.getCode()));
                }

                //集团对接人ids
                String[] dealUserIds = suppliersInspectionRequestVO.getInspectionGroupUserIds().split(",");

                //更新待办
                SMyDeals updateEntity = new SMyDeals();
                //updateEntity.setUserId(userId);
                updateEntity.setDealType(DealTypeEnum.SUPPLIERS.getCode());
                updateEntity.setRelatedId(suppliersInspectionRequestVO.getSuppliersId());
                updateEntity.setSubRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
                updateEntity.setDoneFlag(CommonConstants.NO_INTEGER);
                sMyDealsService.updateSMyDealsByEntity(updateEntity);

                //新增待办
                SMyDeals newEntity = new SMyDeals();
                for (String uId : dealUserIds) {
                    newEntity.setUserId(uId);
                    newEntity.setDealType(DealTypeEnum.SUPPLIERS.getCode());
                    newEntity.setDealSubType(MyDealSubTypeEnum.SITE_INSPECTION.getCode());
                    newEntity.setRelatedId(suppliersInspectionRequestVO.getSuppliersId());
                    newEntity.setSubRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
                    newEntity.setThirdRelatedId(thirdRelatedId);
                    newEntity.setDealTitle(title);
                    newEntity.setActionType(MyDealActionTypeEnum.SITE_INSPECTION_APPLY.getCode());

                    sMyDealsService.saveSMyDeals(newEntity);
                }

                //更新actionType
                SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersInspectionRequestVO.getRcRelatedId());

                if (sSupplierRcRelate != null) {
                    sSupplierRcRelate.setSupplierCategoryIds(suppliersInspectionRequestVO.getIntentionSupplierCategoryIds());
                    sSupplierRcRelate.setActionType(MyDealActionTypeEnum.SITE_INSPECTION_APPLY.getCode());
                    sSupplierRcRelate.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);

                    sSupplierRcRelateService.updateById(sSupplierRcRelate);
                }

            }


            restReturnResult = restReturnResult.success();

            return restReturnResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("===============doSuppliersInspection===e===========:" + e);
            throw new RuntimeException(e.getMessage());
        }

    }

    @Override
    public SuppliersBaseInfoResponseVO getSuppliersBaseInfo(String supplierId, String rcRelatedId, Integer templateType) {
        SuppliersBaseInfoResponseVO result = null;

        LicenseUtil.INSTANCE.validate();
        SSuppliers sSuppliers = sSuppliersService.selectById(supplierId);
        SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(rcRelatedId);
        if (sSuppliers != null && sSupplierRcRelate != null) {
            result = new SuppliersBaseInfoResponseVO();
            BeanUtils.copyProperties(sSuppliers, result);
            result.setSupplierCategoryActualIds(sSupplierRcRelate.getSupplierCategoryActualIds());
            result.setIntentionSupplierCategoryIds(sSupplierRcRelate.getSupplierCategoryIds());
            result.setSupplierStatus(sSupplierRcRelate.getSupplierStatus());
        } else {
            return null;
        }

        //供方与地区公司关联id
        result.setRcRelatedId(rcRelatedId);

        //企业性质
        if (result.getEnterpriseCharacterize() != null) {
            result.setEnterpriseCharacterizeName(EnumConstant.enterpriseCharacterize.getDesc(String.valueOf(result.getEnterpriseCharacterize())));
          /*  if (result.getEnterpriseCharacterize() == NumberUtils.toInteger(""+EnumConstant.enterpriseCharacterize.enterpriseCharacterize1.getCode())) {
                result.setEnterpriseCharacterizeName(EnumConstant.enterpriseCharacterize.enterpriseCharacterize1.getDesc());
            } else if (result.getEnterpriseCharacterize() == NumberUtils.toInteger(""+EnumConstant.enterpriseCharacterize.enterpriseCharacterize2.getCode())) {
                result.setEnterpriseCharacterizeName(EnumConstant.enterpriseCharacterize.enterpriseCharacterize2.getDesc());
            } else if (result.getEnterpriseCharacterize() == NumberUtils.toInteger(""+EnumConstant.enterpriseCharacterize.enterpriseCharacterize3.getCode())) {
                result.setEnterpriseCharacterizeName(EnumConstant.enterpriseCharacterize.enterpriseCharacterize3.getDesc());
            } else if (result.getEnterpriseCharacterize() == NumberUtils.toInteger(""+EnumConstant.enterpriseCharacterize.enterpriseCharacterize4.getCode())) {
                result.setEnterpriseCharacterizeName(EnumConstant.enterpriseCharacterize.enterpriseCharacterize4.getDesc());
            } else if (result.getEnterpriseCharacterize() == NumberUtils.toInteger(""+EnumConstant.enterpriseCharacterize.enterpriseCharacterize5.getCode())) {
                result.setEnterpriseCharacterizeName(EnumConstant.enterpriseCharacterize.enterpriseCharacterize5.getDesc());
            }*/
        }

        //意向地区公司
        result.setIntentionRegionalCompanyNames(sSuppliersService.getRegionalCompanyNamesByIds(result.getIntentionRegionalCompanyIds()));

        //服务地区公司
        result.setServiceRegionalCompanyNames(sSuppliersService.getRegionalCompanyNamesByIds(result.getServiceRegionalCompanyIds()));

        //供方服务类别 (只会有一个)
        String[] supplierServiceCategoryIdArr = {result.getSupplierServiceCategoryIds()};
        result.setSupplierServiceCategoryNames(sSuppliersCategoryService.getSupplierCategoryNames(supplierServiceCategoryIdArr));

        //模板
        result.setSupplierServiceCategoryTemplateNames(sSuppliersCategoryTemplateService.getSupplierCategoryTemplateNames(supplierServiceCategoryIdArr, templateType));

        //供方分类
        String[] supplierCategoryIdArr = result.getSupplierCategoryIds().split(",");
        result.setSupplierCategoryNames(sSuppliersCategoryService.getSupplierCategoryNames(supplierCategoryIdArr));

        //意向供方分类
        if (StringUtils.isNotBlank(result.getIntentionSupplierCategoryIds())) {
            String[] intentionSupplierCategoryIdArr = result.getIntentionSupplierCategoryIds().split(",");
            result.setIntentionsupplierCategoryNames(sSuppliersCategoryService.getSupplierCategoryNames(intentionSupplierCategoryIdArr));
        }

        //供方合格分类
        if (StringUtils.isNotBlank(result.getSupplierCategoryActualIds())) {
            String[] acturalSupplierCategoryIdArr = result.getSupplierCategoryActualIds().split(",");
            result.setSupplierCategoryActualNames(sSuppliersCategoryService.getSupplierCategoryNames(acturalSupplierCategoryIdArr));
        }

//		//考察模板
//		String inspectionTemplateName = result.getSupplierServiceCategoryNames()
//				+ NodeEnum.SITE_INSPECTION + CommonConstants.TEMPLATE;
//		result.setInspectionTemplateName(inspectionTemplateName);

        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> doSuppliersInspectionLeaderAudit(SuppliersInspectionRequestVO suppliersInspectionRequestVO) throws RuntimeException {

        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        LicenseUtil.INSTANCE.validate();
        try {
            String userId = UserUtils.getCurrentUserId();
            if (sMyDealsService.isDone(suppliersInspectionRequestVO.getDealId())) {
                throw new RuntimeException("已完成组长打分，不可重复提交");
            }
            if (!isCompleteReport(suppliersInspectionRequestVO.getId())) {
                throw new RuntimeException("请先填写报告在提交！！");
            }

            boolean workflowFlag = this.checkSiteInspectionByWorkflow(suppliersInspectionRequestVO.getRcRelatedId());
            SSuppliersInspection suppliersInspection = sSuppliersInspectionService.selectById(suppliersInspectionRequestVO.getId());
            if (suppliersInspection == null) {
                throw new RuntimeException("考察报告不存在");
            }

            //供方考察报告-打分明细更新
//            List<SuppliersInspectionScoreRequestVO> lstSuppliersInspectionScoreRequestVO = suppliersInspectionRequestVO.getLstSuppliersInspectionScoreRequestVo();
//            if (lstSuppliersInspectionScoreRequestVO != null && lstSuppliersInspectionScoreRequestVO.size() > 0) {
//                List<SSuppliersInspectionScore> sSuppliersInspectionScoreList = new ArrayList<SSuppliersInspectionScore>();
//                for (SuppliersInspectionScoreRequestVO vo : lstSuppliersInspectionScoreRequestVO) {
//                    SSuppliersInspectionScore score = new SSuppliersInspectionScore();
//                    score.setId(vo.getId());
//                    score.setScores(vo.getScores());
//                    score.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);
//
//                    sSuppliersInspectionScoreList.add(score);
//                }
//
//                sSuppliersInspectionScoreService.updateBatchById(sSuppliersInspectionScoreList);
//            }

            //供方考察报告更新
            if (suppliersInspection != null) {
                suppliersInspection.setLeaderDoneFlag(CommonConstants.YES_INTEGER);
                //suppliersInspection.setInspectionScore(suppliersInspectionRequestVO.getInspectionScore());
                suppliersInspection.setInspectionSuggestion(suppliersInspectionRequestVO.getInspectionSuggestion());
                suppliersInspection.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);

                sSuppliersInspectionService.updateById(suppliersInspection);
            }

            // 附件上传信息保存
            List<AttachmentVO> attachmentVOList = suppliersInspectionRequestVO.getLstAttachments();
            if (attachmentVOList != null && attachmentVOList.size() > 0) {
                List<SAttachment> attachmentList = new ArrayList<SAttachment>();
                attachmentList = ListObjCopyUtil.copyTo(attachmentVOList, SAttachment.class);
                for (SAttachment sAttachment : attachmentList) {
                    sAttachment.setRelatedId(suppliersInspectionRequestVO.getId());
                    sAttachment.setFormId(suppliersInspectionRequestVO.getSuppliersId());
                    sAttachment.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
                }
                sAttachmentService.insertBatch(attachmentList);
            }


            //供应商基本情况及地区公司关联表相关状态变更
            SuppliersAuditRequestVO suppliersAuditRequestVO = new SuppliersAuditRequestVO();
            suppliersAuditRequestVO.setId(suppliersInspectionRequestVO.getSuppliersId());
            suppliersAuditRequestVO.setRcRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
            suppliersAuditRequestVO.setActionType(ActionTypeEnum.LEADER_COMMIT.getCode());

            if (workflowFlag) {
                this.updateSupplierStatusNonMBS(suppliersAuditRequestVO);
            }

            //Step2: 审批历史记录更新
            SHistoryComment sHistoryComment = new SHistoryComment();

            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
            sHistoryComment.setRelatedId(suppliersInspectionRequestVO.getSuppliersId());
            sHistoryComment.setSubRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.LEADER_AUDIT_SITE_INSPECTION_NODE_NAME.getCode()));
            //sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.LEADER_AUDIT_SITE_INSPECTION_COMMENT_CONTENT.getCode()));

            sHistoryComment.setActionName(ActionTypeEnum.LEADER_COMMIT.getDesc());
            sHistoryComment.setAgreeFlag(CommonConstants.AGREE_FLAG);

            sHistoryCommentService.saveSHistoryComment(sHistoryComment);


            SSuppliers sSuppliers = sSuppliersService.selectById(suppliersInspectionRequestVO.getSuppliersId());

            String titleTemplate = sCommentConfigService.getValueByCode(CommentConfigEnum.MY_DEAL_TEMPLATE.getCode());
            String title = MessageFormat.format(titleTemplate, MyDealSubTypeEnum.SITE_INSPECTION.getDesc(), sSuppliers.getCompanyName() + sCommentConfigService.getValueByCode(CommentConfigEnum.SITE_INSPECTION_TEAM_MEMBER_AUDIT_TITLE.getCode()));

            //Step 3: 添加待办已办记录
            String inspectionMemberUserIds = suppliersInspection.getInspectionMemberUserIds();
            if (StringUtils.isNotEmpty(inspectionMemberUserIds)) {
                String[] inspectionMemberUserIdArry = inspectionMemberUserIds.split(",");
                sMyDealsService.dealMyDeals(suppliersInspectionRequestVO.getSuppliersId(), suppliersInspectionRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(), inspectionMemberUserIdArry,
                        MyDealSubTypeEnum.SITE_INSPECTION.getCode(), MyDealActionTypeEnum.TEAM_MEMBER_AUDIT_SITE_INSPECTION.getCode(),
                        title, userId, false, null);

                SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersInspectionRequestVO.getRcRelatedId());
                if (sSupplierRcRelate != null) {
                    sSupplierRcRelate.setActionType(MyDealActionTypeEnum.TEAM_MEMBER_AUDIT_SITE_INSPECTION.getCode());
                    sSupplierRcRelate.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);

                    sSupplierRcRelateService.updateById(sSupplierRcRelate);
                }
            }

            restReturnResult = restReturnResult.success();

            return restReturnResult;

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------doSuppliersInspectionLeaderAudit-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

    @Override
    public SuppliersSiteInspectionBaseInfoVO getSuppliersSiteInspectionBaseInfo(String supplierId, String rcRelatedId, Integer templateType) {

        SuppliersSiteInspectionBaseInfoVO suppliersSiteInspectionBaseInfo = new SuppliersSiteInspectionBaseInfoVO();

        LicenseUtil.INSTANCE.validate();
        //供方基本信息
        SuppliersBaseInfoResponseVO suppliersBaseInfo = this.getSuppliersBaseInfo(supplierId, rcRelatedId, templateType);
        if (suppliersBaseInfo != null) {
            suppliersSiteInspectionBaseInfo.setSuppliersBaseInfoResponseVO(suppliersBaseInfo);
        }

        //考察报告基本信息
        InspectionBaseInfoResponseVO inspectionBaseInfo = this.getInspectionBaseInfo(supplierId, rcRelatedId);
        if (inspectionBaseInfo != null) {
            suppliersSiteInspectionBaseInfo.setInspectionBaseInfoResponseVO(inspectionBaseInfo);
        }

        //组员意见
        if (inspectionBaseInfo != null) {
            List<TeamMembersOpinionVO> teamMembersOpinionInfo = this.getTeamMembersOpinionInfo(inspectionBaseInfo.getId());
            if (teamMembersOpinionInfo != null && teamMembersOpinionInfo.size() > 0) {
                for (TeamMembersOpinionVO obj : teamMembersOpinionInfo) {
                    String userName = sysUserService.getSysUserNameByIds(obj.getCreateBy());
                    if (StringUtils.isNotEmpty(userName)) obj.setCreateByUserName(userName);
                }
                suppliersSiteInspectionBaseInfo.setTeamMembersOpinionVO(teamMembersOpinionInfo);
            }
        }

        //现场考察是否走流程，使用新页面
        if (this.checkSiteInspectionByWorkflow(rcRelatedId)) {
            suppliersSiteInspectionBaseInfo.setSiteInspection(0);
        } else {
            suppliersSiteInspectionBaseInfo.setSiteInspection(1);
        }

        return suppliersSiteInspectionBaseInfo;
    }

    @Override
    public InspectionBaseInfoResponseVO getInspectionBaseInfo(String supplierId, String rcRelatedId) {
        InspectionBaseInfoResponseVO result = null;

        SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(rcRelatedId);
        if (sSupplierRcRelate != null) {

            SSuppliersInspection sSuppliersInspection = sSuppliersInspectionService.getLatestRecordBySuppliersIdAndRegionalCompanyId(supplierId, sSupplierRcRelate.getRegionalCompanyId());
            if (sSuppliersInspection != null) {
                result = new InspectionBaseInfoResponseVO();
                BeanUtils.copyProperties(sSuppliersInspection, result);
                if (StringUtils.isNotBlank(result.getInspectionLeaderUserId())) {
                    result.setInspectionLeaderUserName(sysUserService.getSysUserNameByIds(result.getInspectionLeaderUserId()));
                }
                if (StringUtils.isNotBlank(result.getInspectionMemberUserIds())) {
                    result.setInspectionMemberUserNames(sysUserService.getSysUserNameByIds(result.getInspectionMemberUserIds()));
                }

                if (StringUtils.isNotBlank(result.getInspectionAnnounceUserIds())) {
                    result.setInspectionAnnounceUserNames(sysUserService.getSysUserNameByIds(result.getInspectionAnnounceUserIds()));
                }
                //集团对接人
                if (StringUtils.isNotBlank(result.getInspectionGroupUserIds())) {
                    result.setInspectionGroupUserNames(sysUserService.getSysUserNameByIds(result.getInspectionGroupUserIds()));
                }
                Map<String, Object> map = new HashMap<>();
                map.put("related_id", sSuppliersInspection.getId());
                List<SAttachment> sAttachmentList = sAttachmentService.selectByMap(map);
                if (sAttachmentList != null) {
                    result.setAttachmentList(sAttachmentList);
                }

                //考察公告
                EntityWrapper wrapper = new EntityWrapper();
                SMessages param = new SMessages();
                param.setMsgType(MessagesMsgTypeEnum.MsgType6.getCode()); //现场考察公告
                param.setSubRelatedId(sSuppliersInspection.getId());
                param.setDelFlag(CommonConstants.NO_INTEGER);
                wrapper.setEntity(param);
                SMessages sMessagesDB = sMessagesService.selectOne(wrapper);
                if (sMessagesDB != null) {
                    result.setAnnouncementId(sMessagesDB.getId());
                    result.setAnnouncementName(sMessagesDB.getMsgTitle());
                    result.setAnnouncementContent(sMessagesDB.getMsgContent());
                }
            }
        }

        return result;
    }

    @Override
    public List<TeamMembersOpinionVO> getTeamMembersOpinionInfo(String suppliersInspectionId) {
        if (StringUtils.isBlank(suppliersInspectionId)) {
            return null;
        }
        try {
            List<TeamMembersOpinionVO> result = new ArrayList<TeamMembersOpinionVO>();

            Map<String, Object> map = new HashMap<>();
            map.put("related_id", suppliersInspectionId);
            List<SHistoryComment> historyList = sHistoryCommentService.selectByMap(map);

            result = ListObjCopyUtil.copyTo(historyList, TeamMembersOpinionVO.class);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("===============getTeamMembersOpinionInfo===e===========:" + e);
        }

        return null;

    }

    @Override
    public List<SuppliersInspectionScoreResponseVO> getSuppliersInspectionScoreDetails(
            SuppliersInspectionScoreRequestVO suppliersInspectionScoreRequestVO) {

        LicenseUtil.INSTANCE.validate();
        try {
            SSuppliersInspectionScore sSuppliersInspectionScore = new SSuppliersInspectionScore();
            sSuppliersInspectionScore.setSuppliersInspectionId(suppliersInspectionScoreRequestVO.getSuppliersInspectionId());
            sSuppliersInspectionScore.setDelFlag(CommonConstants.NO_INTEGER);
            EntityWrapper wrapper = new EntityWrapper<>();
            wrapper.setEntity(sSuppliersInspectionScore);

            List<SSuppliersInspectionScore> sSuppliersInspectionScoreList = sSuppliersInspectionScoreService.selectList(wrapper);

            List<SuppliersInspectionScoreResponseVO> suppliersInspectionScoreDetails = ListObjCopyUtil.copyTo(sSuppliersInspectionScoreList, SuppliersInspectionScoreResponseVO.class);

            return suppliersInspectionScoreDetails;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("===============getTeamMembersOpinionInfo===e===========:" + e);
        }

        return null;
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> doSuppliersInspectionMemberAudit(SuppliersInspectionRequestVO suppliersInspectionRequestVO) throws RuntimeException {

        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        try {
            String userId = UserUtils.getCurrentUserId();

//            if(sMyDealsService.isDone(userId,suppliersInspectionRequestVO.getSuppliersId(),
//                    suppliersInspectionRequestVO.getRcRelatedId(),MyDealActionTypeEnum.TEAM_MEMBER_AUDIT_SITE_INSPECTION.getCode())){
//                throw new RuntimeException("重复处理！");
//            }
            if (sMyDealsService.isDone(suppliersInspectionRequestVO.getDealId())) {
                throw new RuntimeException("重复处理！");
            }

            boolean workflowFlag = this.checkSiteInspectionByWorkflow(suppliersInspectionRequestVO.getRcRelatedId());

            //供应商基本情况及地区公司关联表相关状态变更
            SuppliersAuditRequestVO suppliersAuditRequestVO = new SuppliersAuditRequestVO();
            suppliersAuditRequestVO.setId(suppliersInspectionRequestVO.getSuppliersId());
            suppliersAuditRequestVO.setRcRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
            suppliersAuditRequestVO.setActionType(ActionTypeEnum.TEAM_MEMBER_COMMIT.getCode());

            if (workflowFlag) {
                this.updateSupplierStatusNonMBS(suppliersAuditRequestVO);
            }

            //组员会签更新
            SHistoryComment teamMemberAudit = new SHistoryComment();
            teamMemberAudit.setModelType(HistoryCommentModelTypeEnum.TEAM_MEMBERS_OPINIONS_SITE_INSPECTION.getCode());
            teamMemberAudit.setRelatedId(suppliersInspectionRequestVO.getId()); //考察报告id
            teamMemberAudit.setSubRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
            teamMemberAudit.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());
            teamMemberAudit.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.TEAM_MEMBER_AUDIT_SITE_INSPECTION_NODE_NAME.getCode()));
            teamMemberAudit.setCommentContent(suppliersInspectionRequestVO.getComments());


            teamMemberAudit.setActionName(ActionTypeEnum.TEAM_MEMBER_COMMIT.getDesc());
            teamMemberAudit.setAgreeFlag(suppliersInspectionRequestVO.getAgreeFlag());

            sHistoryCommentService.saveSHistoryComment(teamMemberAudit);

            //Step2: 审批历史记录更新
            SHistoryComment sHistoryComment = new SHistoryComment();

            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.TEAM_MEMBERS_OPINIONS_SITE_INSPECTION.getCode());
            sHistoryComment.setRelatedId(suppliersInspectionRequestVO.getSuppliersId());
            sHistoryComment.setSubRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.TEAM_MEMBER_AUDIT_SITE_INSPECTION_NODE_NAME.getCode()));
            //sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.TEAM_MEMBER_AUDIT_SITE_INSPECTION_COMMENT_CONTENT.getCode()));
            sHistoryComment.setCommentContent(suppliersInspectionRequestVO.getComments());

            sHistoryComment.setActionName(ActionTypeEnum.TEAM_MEMBER_COMMIT.getDesc());
            //sHistoryComment.setAgreeFlag(CommonConstants.AGREE_FLAG);
            sHistoryComment.setAgreeFlag(suppliersInspectionRequestVO.getAgreeFlag());

            sHistoryCommentService.saveSHistoryComment(sHistoryComment);

            //Step 3: 添加待办已办记录


            SSuppliersInspection sSuppliersInspection = sSuppliersInspectionService.selectById(suppliersInspectionRequestVO.getId());
//            String inspectionMemberUserIds = sSuppliersInspection.getInspectionMemberUserIds();
//            String[] inspectionMemberUserIdArry = inspectionMemberUserIds.split(",");
//            int memberNums = inspectionMemberUserIdArry.length;

//            SHistoryComment teamMemberAuditParam = new SHistoryComment();
////            teamMemberAuditParam.setRelatedId(suppliersInspectionRequestVO.getId());
////            teamMemberAuditParam.setDelFlag(CommonConstants.NO_INTEGER);
////            EntityWrapper wrapper = new EntityWrapper<>();
////            wrapper.setEntity(teamMemberAuditParam);
////            List<SHistoryComment> teamMemberAuditList = sHistoryCommentService.selectList(wrapper);

            //查询组员未处理的数量
            SMyDeals where = new SMyDeals();
            where.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
            where.setDoneFlag(CommonConstants.UNDONG_FLAG);
            where.setActionType(MyDealActionTypeEnum.TEAM_MEMBER_AUDIT_SITE_INSPECTION.getCode());
            where.setRelatedId(suppliersInspectionRequestVO.getSuppliersId());
            where.setSubRelatedId(suppliersInspectionRequestVO.getRcRelatedId());

            Integer leavecount = sMyDealsService.selectCount(new EntityWrapper<>(where));

            String titleTemplate = sCommentConfigService.getValueByCode(CommentConfigEnum.MY_DEAL_TEMPLATE.getCode());
            if (leavecount == 1) {//所有组员完成会签
                //发起待办
                SSuppliers sSuppliers = sSuppliersService.selectById(suppliersInspectionRequestVO.getSuppliersId());

                String title = MessageFormat.format(titleTemplate, sCommentConfigService.getValueByCode(CommentConfigEnum.SITE_INSPECTION_CHECK_TYPE.getCode()), sSuppliers.getCompanyName()/* + MyDealSubTypeEnum.SITE_INSPECTION.getDesc()*/);

                sMyDealsService.dealMyDeals(suppliersInspectionRequestVO.getSuppliersId(), suppliersInspectionRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(),
                        new String[]{sSuppliersInspection.getCreateBy()}, MyDealSubTypeEnum.SITE_INSPECTION.getCode(),
                        MyDealActionTypeEnum.CHECK_SITE_INSPECTION.getCode(),
                        title, userId, false, null);

                //更新考察报告状态
                sSuppliersInspection.setCountSignDoneFlag(CommonConstants.YES_INTEGER);
                sSuppliersInspection.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);
                sSuppliersInspectionService.updateById(sSuppliersInspection);

                //更新actionType
                SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersInspectionRequestVO.getRcRelatedId());
                if (sSupplierRcRelate != null) {
                    sSupplierRcRelate.setActionType(MyDealActionTypeEnum.CHECK_SITE_INSPECTION.getCode());
                    sSupplierRcRelate.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);

                    sSupplierRcRelateService.updateById(sSupplierRcRelate);
                }

            } else {

                //更新已办
                sMyDealsService.dealMyDeals(suppliersInspectionRequestVO.getSuppliersId(), suppliersInspectionRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(),
                        null, 0, 0, null, userId, false, null);

            }


            restReturnResult = restReturnResult.success();

            return restReturnResult;

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------doSuppliersInspectionMemberAudit-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> checkSuppliersInspection(SuppliersAuditRequestVO suppliersAuditRequestVO) throws RuntimeException {

        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        try {
            SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersAuditRequestVO.getRcRelatedId());
            Integer oldSupplierStatus = sSupplierRcRelate.getSupplierStatus();
            boolean workflowFlag = this.checkSiteInspectionByWorkflow(suppliersAuditRequestVO.getRcRelatedId());

            //供应商基本情况及地区公司关联表相关状态变更
            if (workflowFlag) {
                this.updateSupplierStatusNonMBS(suppliersAuditRequestVO);
            }

            //Step2: 审批历史记录更新
            SHistoryComment sHistoryComment = new SHistoryComment();

            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
            sHistoryComment.setRelatedId(suppliersAuditRequestVO.getId());
            sHistoryComment.setSubRelatedId(suppliersAuditRequestVO.getRcRelatedId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.CHECK_SITE_INSPECTION_NODE_NAME.getCode()));
            //sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.CHECK_SITE_INSPECTION_COMMENT_CONTENT.getCode()));

            sHistoryComment.setActionName(ActionTypeEnumUtil.actionTypeEnumMap.get(suppliersAuditRequestVO.getActionType()));
            if (suppliersAuditRequestVO.getActionType() == ActionTypeEnum.PASS_SITE_INSPECTION.getCode()) {
                sHistoryComment.setAgreeFlag(CommonConstants.AGREE_FLAG);
            } else {
                sHistoryComment.setAgreeFlag(CommonConstants.NO_AGREE_FLAG);
            }

            LicenseUtil.INSTANCE.validate();
            sHistoryCommentService.saveSHistoryComment(sHistoryComment);


            //Step 3: 添加待办已办记录
            String userId = UserUtils.getCurrentUserId();
            SSuppliers sSuppliers = sSuppliersService.selectById(suppliersAuditRequestVO.getId());

            String titleTemplate = sCommentConfigService.getValueByCode(CommentConfigEnum.MY_DEAL_TEMPLATE.getCode());


            if (suppliersAuditRequestVO.getActionType() == ActionTypeEnum.PASS_SITE_INSPECTION.getCode()) {
                sSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersAuditRequestVO.getRcRelatedId());
                sSupplierRcRelate.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);
                sSupplierRcRelate.setSupplierCategoryIds(suppliersAuditRequestVO.getIntentionSupplierCategoryIds());

                String supplierCategoryActualIds = null;
                sSupplierRcRelate.setSupplierCategoryIds(suppliersAuditRequestVO.getIntentionSupplierCategoryIds());
                if (StringUtils.isNotBlank(sSupplierRcRelate.getSupplierCategoryActualIds())) {
                    supplierCategoryActualIds = sSupplierRcRelate.getSupplierCategoryActualIds() + "," + suppliersAuditRequestVO.getIntentionSupplierCategoryIds();
                } else {
                    supplierCategoryActualIds = suppliersAuditRequestVO.getIntentionSupplierCategoryIds();
                }
                if (StringUtils.isNotBlank(supplierCategoryActualIds)) {
                    sSupplierRcRelate.setSupplierCategoryActualIds(supplierCategoryActualIds);
                }

                String title = MessageFormat.format(titleTemplate, MyDealSubTypeEnum.STORE_APPOVE.getDesc(), sSuppliers.getCompanyName()/* + MyDealSubTypeEnum.SITE_INSPECTION.getDesc()*/);

                //考察报告更新;
                if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getReportId())) {
                    SSuppliersInspection sSuppliersInspection = sSuppliersInspectionService.selectById(suppliersAuditRequestVO.getReportId());

                    if (sSuppliersInspection != null) {
                        sSuppliersInspection.setSupplierCategoryActualIds(suppliersAuditRequestVO.getIntentionSupplierCategoryIds());
                        sSuppliersInspection.setDoneFlag(CommonConstants.YES_INTEGER);
                        sSuppliersInspection.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);

                        sSuppliersInspectionService.updateById(sSuppliersInspection);
                    }

                }

                if (sSupplierRcRelate != null) {
                    sSupplierRcRelateService.updateById(sSupplierRcRelate);
                }


                if (workflowFlag) {
                    sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), suppliersAuditRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(), new String[]{userId},
                            MyDealSubTypeEnum.STORE_APPOVE.getCode(), MyDealActionTypeEnum.STORE_APPOVE.getCode(),
                            title, userId, true, null);
                } else {
                    sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), suppliersAuditRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(),
                            null, 0, 0, null, userId, true, null);
                }

            } else if (suppliersAuditRequestVO.getActionType() == ActionTypeEnum.UNPASS_SITE_INSPECTION.getCode()) {

                SMessages message = new SMessages();
                message.setUserIds(sSuppliers.getSysUserId());
                message.setMsgType(MessagesMsgTypeEnum.ANNOUNCEMENT_NOTICE.getCode());
                message.setMsgTitle(sCommentConfigService.getValueByCode(CommentConfigEnum.SITE_INSPECTION_UNPASS.getCode())
                        .replace("{0}", sRegionalCompanyService.getRegionalCompanyNames(new String[]{sSupplierRcRelate.getRegionalCompanyId()})));
                message.setMsgContent(suppliersAuditRequestVO.getComments());

                sMessagesService.addSMessages(message);

                //考察报告更新;
                if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getReportId())) {
                    SSuppliersInspection sSuppliersInspection = sSuppliersInspectionService.selectById(suppliersAuditRequestVO.getReportId());

                    if (sSuppliersInspection != null) {
                        sSuppliersInspection.setDoneFlag(CommonConstants.YES_INTEGER);
                        sSuppliersInspection.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);

                        sSuppliersInspectionService.updateById(sSuppliersInspection);
                    }

                }

                //更新已办
                sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), suppliersAuditRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(),
                        null, 0, 0, null, userId, true, null);

            } else if (suppliersAuditRequestVO.getActionType() == ActionTypeEnum.TURN_TO_PENDING_WATCH.getCode()) {

                SMessages message = new SMessages();
                message.setUserIds(sSuppliers.getSysUserId());
                message.setMsgType(MessagesMsgTypeEnum.ANNOUNCEMENT_NOTICE.getCode());
                message.setMsgTitle(sCommentConfigService.getValueByCode(CommentConfigEnum.TURN_TO_PENDING_WATCH.getCode())
                        .replace("{0}", sRegionalCompanyService.getRegionalCompanyNames(new String[]{sSupplierRcRelate.getRegionalCompanyId()})));
                message.setMsgContent(suppliersAuditRequestVO.getComments());

                sMessagesService.addSMessages(message);

                //考察报告更新;
                if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getReportId())) {
                    SSuppliersInspection sSuppliersInspection = sSuppliersInspectionService.selectById(suppliersAuditRequestVO.getReportId());

                    if (sSuppliersInspection != null) {
                        sSuppliersInspection.setDoneFlag(CommonConstants.YES_INTEGER);
                        sSuppliersInspection.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);

                        sSuppliersInspectionService.updateById(sSuppliersInspection);
                    }

                }

                //更新已办
                sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), suppliersAuditRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(),
                        null, 0, 0, null, userId, true, null);

                if (!SupplierStatusEnum.SITE_INSPECTION_ING.getCode().equals(String.valueOf(oldSupplierStatus))) {
//                    sSupplierRcRelate.setSupplierCategoryActualIds("");
////                    sSupplierRcRelateService.updateById(sSupplierRcRelate);

                    sSupplierRcRelateService.emptyActualIdsById(sSupplierRcRelate.getId());
                }
            }

            LicenseUtil.INSTANCE.validate();
            restReturnResult = restReturnResult.success();

            return restReturnResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------checkSuppliersInspection-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> setupSupplierStorageProcess(SuppliersAuditRequestVO suppliersAuditRequestVO) throws RuntimeException {

        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        try {
            ExtSSuppliers sSuppliers = extSSuppliersMapper.getByRelatedId(suppliersAuditRequestVO.getRcRelatedId());

            SessionUserVo currentUserVo = UserUtils.getCurrentUserVo();
            if (currentUserVo == null) {
                throw new RuntimeException("未获取到当前操作人信息，请登录后重试");
            }
            String userId = currentUserVo.getEmployeeID();


            LicenseUtil.INSTANCE.validate();
            //TODO:BPM入库审核，对接
            String ITEM_KIND_CODE = "";
            String qualifiedCategoryIds = sSuppliers.getQualifiedCategoryIds();
            String supplierCategoryIds = sSuppliers.getSupplierCategoryIds();
            if (StringUtils.isNotEmpty(qualifiedCategoryIds)) {
//                String categoryId=qualifiedCategoryIds.split(",")[0];
//                SSuppliersCategory sSuppliersCategory=sSuppliersCategoryService.selectById(categoryId);
//                if(sSuppliersCategory!=null&&StringUtils.isNotEmpty(sSuppliersCategory.getCategoryCode())){
//                    ITEM_KIND_CODE=sSuppliersCategory.getCategoryCode();
//                }
                String[] categoryIds = qualifiedCategoryIds.split(",");
                List<String> categoryIdList = Arrays.asList(categoryIds);
                List<SSuppliersCategory> sSuppliersCategoryList = sSuppliersCategoryService.selectBatchIds(categoryIdList);
                if (sSuppliersCategoryList != null && sSuppliersCategoryList.size() > 0) {
                    for (SSuppliersCategory sSuppliersCategory : sSuppliersCategoryList) {
                        String categoryCode = sSuppliersCategory.getCategoryCode();
                        if (categoryCode.indexOf("A") > 0) {
                            ITEM_KIND_CODE = categoryCode;
                            break;
                        }
                    }

                    if (StringUtils.isBlank(ITEM_KIND_CODE)) {
                        ITEM_KIND_CODE = sSuppliersCategoryList.get(0).getCategoryCode();
                    }

                }

            } else if (StringUtils.isNotEmpty(supplierCategoryIds) && StringUtils.isEmpty(ITEM_KIND_CODE)) {
//                String categoryId=supplierCategoryIds.split(",")[0];
//                SSuppliersCategory sSuppliersCategory=sSuppliersCategoryService.selectById(categoryId);
//                if(sSuppliersCategory!=null&&StringUtils.isNotEmpty(sSuppliersCategory.getCategoryCode())){
//                    ITEM_KIND_CODE=sSuppliersCategory.getCategoryCode();
//                }
                String[] categoryIds = supplierCategoryIds.split(",");
                List<String> categoryIdList = Arrays.asList(categoryIds);
                List<SSuppliersCategory> sSuppliersCategoryList = sSuppliersCategoryService.selectBatchIds(categoryIdList);
                if (sSuppliersCategoryList != null && sSuppliersCategoryList.size() > 0) {
                    for (SSuppliersCategory sSuppliersCategory : sSuppliersCategoryList) {
                        String categoryCode = sSuppliersCategory.getCategoryCode();
                        if (categoryCode.indexOf("A") > 0) {
                            ITEM_KIND_CODE = categoryCode;
                            break;
                        }
                    }

                    if (StringUtils.isBlank(ITEM_KIND_CODE)) {
                        ITEM_KIND_CODE = sSuppliersCategoryList.get(0).getCategoryCode();
                    }

                }
            }

            if (StringUtils.isEmpty(ITEM_KIND_CODE)) {
                return new RestReturnResult<Object>(CommonConstants.FAIL, "", CommonConstants.ERROR_NO_PURCHASE_CATEGEORY_CODE_FAIL, "");
            }

            //供应商基本情况及地区公司关联表相关状态变更
            this.updateSupplierStatusNonMBS(suppliersAuditRequestVO);

            //Step2: 审批历史记录更新
            SHistoryComment sHistoryComment = new SHistoryComment();

            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
            sHistoryComment.setRelatedId(suppliersAuditRequestVO.getId());
            sHistoryComment.setSubRelatedId(suppliersAuditRequestVO.getRcRelatedId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.LAUNCH_STORE_APPROVE_NODE_NAME.getCode()));
            sHistoryComment.setCommentContent(suppliersAuditRequestVO.getComments());

            sHistoryComment.setActionName(ActionTypeEnumUtil.actionTypeEnumMap.get(suppliersAuditRequestVO.getActionType()));
            sHistoryComment.setAgreeFlag(CommonConstants.AGREE_FLAG);

            sHistoryCommentService.saveSHistoryComment(sHistoryComment);


            Map<String, Object> mapParams = new HashMap<String, Object>();
            mapParams.put("CURRENT_USER_ID", userId);
            mapParams.put("CURRENT_USER_NAME", currentUserVo.getUserName());
            mapParams.put("CURRENT_DEPT_CODE", currentUserVo.getDept());
            mapParams.put("RELATE_ID", suppliersAuditRequestVO.getId());
            mapParams.put("SUB_RELATE_ID", suppliersAuditRequestVO.getRcRelatedId());
            mapParams.put("ITEM_KIND_CODE", ITEM_KIND_CODE);

            mapParams.put("ORG_CODE", currentUserVo.getCompanyCode());
            mapParams.put("ORG_NAME", currentUserVo.getsCompanyName());
            mapParams.put("EMPLOYEE_CODE", currentUserVo.getEmployeeID());

//            mapParams.get("ORG_CODE");
//            mapParams.get("ORG_NAME");
//            mapParams.get("EMPLOYEE_CODE");
//            mapParams.get("ITEM_KIND_CODE");
            mapParams.put("supplier", sSuppliers);
            mapParams.put("flowKind", suppliersAuditRequestVO.getFlowKind());
            Map<String, Object> mapBpmParams = bpmUtil.invokeApprovalFlow(mapParams, AbutmentSubTypeEnum.STORE_APPROVE.getCode());
            Boolean isSuccess = (Boolean) mapBpmParams.get("IS_SUCCESS");
            String mbsUrl = (String) mapBpmParams.get("MBS_URL");
            if (isSuccess == false) {
                throw new RuntimeException("BPM入库审核对接失败");
            } else {
                SHistoryComment updateSHistoryComment = new SHistoryComment();
                updateSHistoryComment.setId(sHistoryComment.getId());
                updateSHistoryComment.setCommentUrl(mbsUrl);
                sHistoryCommentService.updateById(updateSHistoryComment);
            }
            LicenseUtil.INSTANCE.validate();

            //Step 3: 更新已办

//            SSuppliers sSuppliers = sSuppliersService.selectById(suppliersAuditRequestVO.getId());

            sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), suppliersAuditRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(),
                    null, 0, 0, null, userId, true, null);

            restReturnResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, mbsUrl, null, "操作成功");

            return restReturnResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------setupSupplierStorageProcess-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }


    /**
     * MBS系统回调处理（审批通过/审批不通过）
     *
     * @param suppliersAuditRequestVO
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public void doSupplierStorageProcess(SuppliersAuditRequestVO suppliersAuditRequestVO) throws RuntimeException {
        try {
            SSuppliers sSuppliers = sSuppliersService.selectById(suppliersAuditRequestVO.getId());
            if (sSuppliers == null) {
                throw new RuntimeException("数据不存在");
            }

            SSupplierRcRelate sSupplierRcRelate = null;
            if (sSuppliers.getSupplierBigStatus() != null && sSuppliers.getSupplierBigStatus() != SupplierBigStatusEnum.BLACK_LIBRARY.getCode()) {
                sSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersAuditRequestVO.getRcRelatedId());
                if (sSupplierRcRelate == null) {
                    throw new RuntimeException("子表数据不存在");
                }
            }
            boolean isNew = true;
            if (sSuppliers.getSupplierBigStatus() != null && sSuppliers.getSupplierBigStatus() != SupplierBigStatusEnum.QUALIFIED.getCode()) {
                isNew = false;
            }

            if (suppliersAuditRequestVO.getActionType() == ActionTypeEnum.PASSS_AUDIT.getCode() || suppliersAuditRequestVO.getActionType() == ActionTypeEnum.UNPASS_AUDIT.getCode()) {
                //Step2: 审批历史记录更新
                SHistoryComment sHistoryComment = new SHistoryComment();
                if (suppliersAuditRequestVO.getActionType() == ActionTypeEnum.PASSS_AUDIT.getCode()) {
                    sHistoryComment.setAgreeFlag(CommonConstants.AGREE_FLAG);
                } else if (suppliersAuditRequestVO.getActionType() == ActionTypeEnum.UNPASS_AUDIT.getCode()) {
                    sHistoryComment.setAgreeFlag(CommonConstants.NO_AGREE_FLAG);
                }
                sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
                sHistoryComment.setRelatedId(suppliersAuditRequestVO.getId());
                if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getRcRelatedId())) {
                    sHistoryComment.setSubRelatedId(suppliersAuditRequestVO.getRcRelatedId());
                } else {
                    sHistoryComment.setSubRelatedId(suppliersAuditRequestVO.getId());
                }
                LicenseUtil.INSTANCE.validate();
                sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用

                if (AbutmentSubTypeEnum.STORE_APPROVE.getCode() == suppliersAuditRequestVO.getAbutmentSubType()) { //入库审批

                    sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_STORE_APPROVE_NODE_NAME.getCode()));
                    if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getComments())) {
                        sHistoryComment.setCommentContent(suppliersAuditRequestVO.getComments());
                    } else {
                        sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_STORE_APPROVE_COMMENT_CONTENT.getCode()));
                    }

                } else if (AbutmentSubTypeEnum.TURN_TO_PENDING_WATCH_APPROVE.getCode() == suppliersAuditRequestVO.getAbutmentSubType()) {//转待观察审批

                    sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_QUALIFIED_TURN_TO_PENDING_WATCH_NODE_NAME.getCode()));
                    if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getComments())) {
                        sHistoryComment.setCommentContent(suppliersAuditRequestVO.getComments());
                    } else {
                        sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_QUALIFIED_TURN_TO_PENDING_WATCH_CONTENT.getCode()));
                    }

                } else if (AbutmentSubTypeEnum.TURN_TO_UNQUALIFIED_APPROVE.getCode() == suppliersAuditRequestVO.getAbutmentSubType()) {//转不合格审批

                    sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_QUALIFIED_TURN_TO_UNQUALIFIED_NODE_NAME.getCode()));
                    if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getComments())) {
                        sHistoryComment.setCommentContent(suppliersAuditRequestVO.getComments());
                    } else {
                        sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_QUALIFIED_TURN_TO_UNQUALIFIED_COMMENT_CONTENT.getCode()));
                    }

                } else if (AbutmentSubTypeEnum.TURN_TO_POTENTIAL_APPROVE.getCode() == suppliersAuditRequestVO.getAbutmentSubType()) {//转潜在审批
                    if (sSuppliers.getSupplierBigStatus() == SupplierBigStatusEnum.BLACK_LIBRARY.getCode()) {
                        sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_BLACK_LIBRARY_TURN_TO_POTENTIAL_NODE_NAME.getCode()));
                        if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getComments())) {
                            sHistoryComment.setCommentContent(suppliersAuditRequestVO.getComments());
                        } else {
                            sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_BLACK_LIBRARY_TURN_TO_POTENTIAL_COMMENT_CONTENT.getCode()));
                        }
                    } else {
                        if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.UNQUALIFIED.getCode()) {
                            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_UNQUALIFIED_TURN_TO_POTENTIAL_NODE_NAME.getCode()));
                            if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getComments())) {
                                sHistoryComment.setCommentContent(suppliersAuditRequestVO.getComments());
                            } else {
                                sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_UNQUALIFIED_TURN_TO_POTENTIAL_COMMENT_CONTENT.getCode()));
                            }
                        }
                    }
                } else if (AbutmentSubTypeEnum.TURN_TO_BLACK_LIBRARY_APPROVE.getCode() == suppliersAuditRequestVO.getAbutmentSubType()) {//转黑库审批
                    if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.QUALIFIED.getCode()) {
                        sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_QUALIFIED_TURN_TO_BLACK_LIBRARY_NODE_NAME.getCode()));
                        if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getComments())) {
                            sHistoryComment.setCommentContent(suppliersAuditRequestVO.getComments());
                        } else {
                            sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_QUALIFIED_TURN_TO_BLACK_LIBRARY_COMMENT_CONTENT.getCode()));
                        }
                    } else if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.UNQUALIFIED.getCode()) {
                        sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_UNQUALIFIED_TURN_TO_BLACK_LIBRARY_NODE_NAME.getCode()));
                        if (StringUtils.isNotEmpty(suppliersAuditRequestVO.getComments())) {
                            sHistoryComment.setCommentContent(suppliersAuditRequestVO.getComments());
                        } else {
                            sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.BPM_UNQUALIFIED_TURN_TO_BLACK_LIBRARY_COMMENT_CONTENT.getCode()));
                        }
                    }
                }

                sHistoryComment.setActionName(ActionTypeEnumUtil.actionTypeEnumMap.get(suppliersAuditRequestVO.getActionType()));
                sHistoryComment.setCommentUrl(suppliersAuditRequestVO.getAbutmentDetailUrl());
                sHistoryCommentService.saveSHistoryComment(sHistoryComment);


                //供应商基本情况及地区公司关联表相关状态变更，同步到主数据系统
                this.updateSupplierStatusByMBS(suppliersAuditRequestVO, isNew);
            }
            //Step 3: 更新已办
//			sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), 0, null, 0, 0, null);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------doSupplierStorageProcess-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public RestReturnResult<Object> doToDoItem(String myDealId) {
        RestReturnResult restReturnResult = RestReturnResult.error();

        DoMyDealsResponseVO doMyDealsResponseVO = new DoMyDealsResponseVO();

        LicenseUtil.INSTANCE.validate();
        SMyDeals sMyDeals = sMyDealsService.selectUntreatedById(myDealId);
        if (sMyDeals != null) {
            if (sMyDeals.getDealType() == DealTypeEnum.SUPPLIERS.getCode()) {

                SSuppliers sSuppliers = sSuppliersService.selectById(sMyDeals.getRelatedId());
                //是否引入
                doMyDealsResponseVO.setIncursionFlag(sSuppliers.getIncursionFlag());

                doMyDealsResponseVO.setDealActionType(sMyDeals.getActionType());
                //供应商详情（基本情况+近三年...）
                if (sMyDeals.getActionType() == MyDealActionTypeEnum.QUALIFICATION_INSPECTION.getCode()
                        || sMyDeals.getActionType() == MyDealActionTypeEnum.STORE_APPOVE.getCode()) { //资质审查\入库审批
                    RestReturnResult<SuppliersDetailVO> returnResult = sSuppliersService.getSuppliersById(sMyDeals.getRelatedId());
                    SuppliersDetailVO suppliersDetailVO = returnResult.getData();

                    doMyDealsResponseVO.setSuppliersDetailVO(suppliersDetailVO);
                }

                //现场考察基本信息
                if (sMyDeals.getActionType() == MyDealActionTypeEnum.SITE_INSPECTION.getCode()) {//现场考察
                    SuppliersBaseInfoResponseVO suppliersBaseInfoResponseVO = this.getSuppliersBaseInfo(sMyDeals.getRelatedId(), sMyDeals.getSubRelatedId(), CommonConstants.TEMPLATE_CATEGORY_1);

                    SuppliersSiteInspectionBaseInfoVO suppliersSiteInspectionBaseInfoVO = new SuppliersSiteInspectionBaseInfoVO();
                    suppliersSiteInspectionBaseInfoVO.setSuppliersBaseInfoResponseVO(suppliersBaseInfoResponseVO);

                    doMyDealsResponseVO.setSuppliersSiteInspectionBaseInfoVO(suppliersSiteInspectionBaseInfoVO);
                } else if (sMyDeals.getActionType() == MyDealActionTypeEnum.LEADER_AUDIT_SITE_INSPECTION.getCode()
                        || sMyDeals.getActionType() == MyDealActionTypeEnum.TEAM_MEMBER_AUDIT_SITE_INSPECTION.getCode()) {//队长打分\会员组签
                    SuppliersBaseInfoResponseVO suppliersBaseInfoResponseVO = this.getSuppliersBaseInfo(sMyDeals.getRelatedId(), sMyDeals.getSubRelatedId(), CommonConstants.TEMPLATE_CATEGORY_1);
                    InspectionBaseInfoResponseVO inspectionBaseInfoResponseVO = this.getInspectionBaseInfo(sMyDeals.getRelatedId(), sMyDeals.getSubRelatedId());

                    SuppliersSiteInspectionBaseInfoVO suppliersSiteInspectionBaseInfoVO = new SuppliersSiteInspectionBaseInfoVO();
                    suppliersSiteInspectionBaseInfoVO.setSuppliersBaseInfoResponseVO(suppliersBaseInfoResponseVO);
                    suppliersSiteInspectionBaseInfoVO.setInspectionBaseInfoResponseVO(inspectionBaseInfoResponseVO);

                    doMyDealsResponseVO.setSuppliersSiteInspectionBaseInfoVO(suppliersSiteInspectionBaseInfoVO);
                } else if (sMyDeals.getActionType() == MyDealActionTypeEnum.CHECK_SITE_INSPECTION.getCode()) {//现场考察审核
                    SuppliersBaseInfoResponseVO suppliersBaseInfoResponseVO = this.getSuppliersBaseInfo(sMyDeals.getRelatedId(), sMyDeals.getSubRelatedId(), CommonConstants.TEMPLATE_CATEGORY_1);
                    InspectionBaseInfoResponseVO inspectionBaseInfoResponseVO = this.getInspectionBaseInfo(sMyDeals.getRelatedId(), sMyDeals.getSubRelatedId());
                    List<TeamMembersOpinionVO> teamMembersOpinionVO = this.getTeamMembersOpinionInfo(inspectionBaseInfoResponseVO.getId());

                    SuppliersSiteInspectionBaseInfoVO suppliersSiteInspectionBaseInfoVO = new SuppliersSiteInspectionBaseInfoVO();
                    suppliersSiteInspectionBaseInfoVO.setSuppliersBaseInfoResponseVO(suppliersBaseInfoResponseVO);
                    suppliersSiteInspectionBaseInfoVO.setInspectionBaseInfoResponseVO(inspectionBaseInfoResponseVO);
                    suppliersSiteInspectionBaseInfoVO.setTeamMembersOpinionVO(teamMembersOpinionVO);

                    doMyDealsResponseVO.setSuppliersSiteInspectionBaseInfoVO(suppliersSiteInspectionBaseInfoVO);
                }
            }

            restReturnResult = restReturnResult.success();
            restReturnResult.setData(doMyDealsResponseVO);
        }

        return restReturnResult;
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> supplierImport(String supplierId, String regionalCompanyId) throws RuntimeException {

        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        LicenseUtil.INSTANCE.validate();
        try {
            SSuppliers sSuppliers = sSuppliersService.selectById(supplierId);
//			if(CommonConstants.YES_INTEGER == sSuppliers.getIncursionFlag()){//正在引入中
//				restReturnResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, "供方正被其他地区公司（集团）引入中，不允许同时引入！");
//				return restReturnResult;
//			}

            SessionUserVo sessionUserVo = UserUtils.getCurrentUserVo();
            String userId = sessionUserVo.getEmployeeID();
            //String regionalCompanyId=sessionUserVo.getsRegionalCompanyId();
            if (StringUtils.isEmpty(regionalCompanyId)) {
                restReturnResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, "当前登录人地区公司不存在！");
                return restReturnResult;
            }

            //添加意向地区公司关联
            if (StringUtils.isNotEmpty(regionalCompanyId)) {
                EntityWrapper rcRelateWrapper = new EntityWrapper();
                SSupplierRcRelate rcRelateObj = new SSupplierRcRelate();
                rcRelateObj.setSuppliersId(supplierId);
                rcRelateObj.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
                rcRelateObj.setRegionalCompanyId(regionalCompanyId);
                rcRelateWrapper.setEntity(rcRelateObj);
                int count = sSupplierRcRelateService.selectCount(rcRelateWrapper);
                if (count > 0) {
                    restReturnResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, "已存在，无需引入");
                    return restReturnResult;
                }
                //意向地区公司
//                if(StringUtils.isNotEmpty(sSuppliers.getIntentionRegionalCompanyIds())){
//                    String[]  values=sSuppliers.getIntentionRegionalCompanyIds().split(",");
//                    List<String> list = Arrays.asList(values);
//                    if(!list.contains(regionalCompanyId)){
//                        sSuppliers.setIntentionRegionalCompanyIds(sSuppliers.getIntentionRegionalCompanyIds()+","+regionalCompanyId);
//                    }
//                }else{
//                    sSuppliers.setIntentionRegionalCompanyIds(regionalCompanyId);
//                }
//                sSuppliersService.updateById(sSuppliers);
            } else {
                return RestReturnResult.error();
            }
            SSupplierRcRelate sSupplierRcRelate = new SSupplierRcRelate();
            String rcRelatedId = IdGenUtils.uuid();
            sSupplierRcRelate.setId(rcRelatedId);
            sSupplierRcRelate.setSuppliersId(supplierId);
//
//			SRegionalCompany regionalCompany = sRegionalCompanyService.getRegionalCompanyByMngUser(userId);
            sSupplierRcRelate.setRegionalCompanyId(regionalCompanyId);
            sSupplierRcRelate.setSupplierCategoryIds(sSuppliers.getSupplierCategoryIds());
            sSupplierRcRelate.setSupplierServiceCategoryIds(sSuppliers.getSupplierServiceCategoryIds());
            sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.SITE_INSPECTION.getCode()));
            sSupplierRcRelate.setFirstStoredFlag(CommonConstants.NO_INTEGER);
            sSupplierRcRelate.setSupplierSource(SupplierSourceEnum.INCURSION.getCode());
            sSupplierRcRelate.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());
            sSupplierRcRelate.setBaseFeilds(userId, null, 0, true);
            boolean rcRelateflag = sSupplierRcRelateService.insert(sSupplierRcRelate);


            if (rcRelateflag) {
                //更新供方基本情况
                sSuppliers.setIncursionFlag(CommonConstants.YES_INTEGER);
                sSuppliersService.updateById(sSuppliers);

                //Step: 审批历史记录更新
                SHistoryComment sHistoryComment = new SHistoryComment();

                sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
                sHistoryComment.setRelatedId(supplierId);
                sHistoryComment.setSubRelatedId(rcRelatedId);
                sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
                sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.IMPORT_NODE_NAME.getCode()));
                sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.IMPORT_COMMENT_CONTENT.getCode()));

                sHistoryComment.setActionName(ActionTypeEnum.IMPORT.getDesc());
                sHistoryComment.setAgreeFlag(CommonConstants.AGREE_FLAG);

                sHistoryCommentService.saveSHistoryComment(sHistoryComment);

                //Step:更新待办已办

                String titleTemplate = sCommentConfigService.getValueByCode(CommentConfigEnum.MY_DEAL_TEMPLATE.getCode());
                String title = MessageFormat.format(titleTemplate, MyDealSubTypeEnum.SITE_INSPECTION.getDesc(), sSuppliers.getCompanyName());

                sMyDealsService.dealMyDeals(supplierId, rcRelatedId, DealTypeEnum.SUPPLIERS.getCode(), new String[]{userId},
                        MyDealSubTypeEnum.SITE_INSPECTION.getCode(), MyDealActionTypeEnum.SITE_INSPECTION.getCode(),
                        title, userId, false, null);

                restReturnResult = new RestReturnResult<Object>(CommonConstants.SUCCESS);
            } else {
                restReturnResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[8], CommonConstants.ERROR_DESCS[8]);
            }

            return restReturnResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------supplierImport-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> supplierAlterationAudit(SuppliersAuditRequestVO suppliersAuditRequestVO) throws RuntimeException {

        LicenseUtil.INSTANCE.validate();
        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        try {
            //审批历程
            String sHistoryCommentId = IdGen.uuid();
            SHistoryComment sHistoryComment = new SHistoryComment();
            sHistoryComment.setId(sHistoryCommentId);
            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
            sHistoryComment.setRelatedId(suppliersAuditRequestVO.getId());
            sHistoryComment.setSubRelatedId(suppliersAuditRequestVO.getRcRelatedId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTERNET.getCode());  //内外网共用
            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.ALTERATION_AUDIT_NODE_NAME.getCode()));
            sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.ALTERATION_AUDIT_COMMENT_CONTENT.getCode()));

            //外网消息
            SMessages sMessage = new SMessages();

            if (suppliersAuditRequestVO.getActionType() == ActionTypeEnum.REFUSE_ALTERATION.getCode()) { //打回

                //信息回滚
                sSuppliersService.fallbackSuppliers(suppliersAuditRequestVO.getId(), EnumConstant.AuditStatus.reject.getCode(), sHistoryCommentId);

                sHistoryComment.setActionName(ActionTypeEnum.REFUSE_ALTERATION.getDesc());
                sHistoryComment.setAgreeFlag(CommonConstants.NO_AGREE_FLAG);
                SCommentConfig sCommentConfig = sCommentConfigService.getByCode(CommentConfigEnum.ALTERATION_AUDIT_UNPASS.getCode());
                sMessage.setMsgTitle(sCommentConfig.getConfigValue());
                sMessage.setJumpFlag(sCommentConfig.getJumpFlag());
            } else if (suppliersAuditRequestVO.getActionType() == ActionTypeEnum.PASS_ALTERATION.getCode()) { //变更审核通过
                sSuppliersService.fallbackSuppliers(suppliersAuditRequestVO.getId(), EnumConstant.AuditStatus.agree.getCode(), sHistoryCommentId);

                sHistoryComment.setActionName(ActionTypeEnum.PASS_ALTERATION.getDesc());
                sHistoryComment.setAgreeFlag(CommonConstants.AGREE_FLAG);

                SCommentConfig sCommentConfig = sCommentConfigService.getByCode(CommentConfigEnum.ALTERATION_AUDIT_PASS.getCode());
                sMessage.setMsgTitle(sCommentConfig.getConfigValue());
                sMessage.setJumpFlag(sCommentConfig.getJumpFlag());

                //同步供应商数据到旧系统
                SSuppliers sSuppliers = sSuppliersService.selectById(suppliersAuditRequestVO.getId());
//                sSuppliersSubmitOldSysInterfaceService.abutmentSuplierData(sSuppliers, false);
                sSuppliersSubmitOldSysInterfaceService.abutmentSuplierData2MDM(sSuppliers, false);
            }

            SSuppliers updateModify = new SSuppliers();
            updateModify.setId(suppliersAuditRequestVO.getId());
            updateModify.setModifiedFlag(0);
            sSuppliersService.updateById(updateModify);

            String userId = UserUtils.getCurrentUserId();

            sMessage.setUserIds(sSuppliersService.getById(suppliersAuditRequestVO.getId()).getSysUserId());
            sMessage.setMsgType(MessagesMsgTypeEnum.ANNOUNCEMENT_NOTICE.getCode());
            sMessage.setMsgContent(suppliersAuditRequestVO.getComments());
            sMessage.setFlowFormId(suppliersAuditRequestVO.getId());
            sMessage.setBaseFeilds(userId, null, 0, true);
            sMessagesService.insert(sMessage);

            //审批历程
            sHistoryCommentService.saveSHistoryComment(sHistoryComment);

            //待办已办处理

            sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), suppliersAuditRequestVO.getId(), MyDealActionTypeEnum.SUPPLIERS_CHANGE.getCode());

            restReturnResult = restReturnResult.success();

            return restReturnResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------supplierAlterationAudit-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> turnToPendingWatch(TransferRequestVO transferRequestVO) throws RuntimeException {

        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        try {

            //TODO:判断合格供应商是否能够转待观察(合格列表两年内无合作的供方可转,校验逻辑待确认)
//			WFlowFormAwardBid wFlowFormAwardBid = wFlowFormAwardBidService.getSupplierAwardBidBySupplierIdAndCooperationYears(supplierId, CommonConstants.COOPERATION_YEARS);
//			if(wFlowFormAwardBid == null){
//				restReturnResult = new RestReturnResult<Object>(CommonConstants.FAIL, );
//			}
            String subSupplierId = transferRequestVO.getRcRelatedId();
            if (StringUtils.isEmpty(subSupplierId)) {
                throw new RuntimeException("id为空");
            }
            LicenseUtil.INSTANCE.validate();
            SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(subSupplierId);
//            SSuppliers sSuppliers=sSuppliersService.selectById(transferRequestVO.getSupplierId());
            if (sSupplierRcRelate == null) {
                throw new RuntimeException("供方数据不存在");
            }
            if (!SupplierStatusEnum.QUALIFIED.getCode().equals(sSupplierRcRelate.getSupplierStatus() + "")) {
                throw new RuntimeException("只有合格供方可以转待观察");
            }
            sSupplierRcRelate.setTurnToWatchDesc(transferRequestVO.getRemarks());
            sSupplierRcRelate.setSupplierStatus(Integer.valueOf(SupplierStatusEnum.TURN_TO_PENDING_WATCH.getCode()));
            sSupplierRcRelate.setTurnToWatchTime(new Date());
            sSupplierRcRelate.setSupplierCategoryActualIds("");
//            sSuppliersService.updateById(sSuppliers);
            sSupplierRcRelateService.updateById(sSupplierRcRelate);

//            List<SSupplierRcRelate>  sSupplierRcRelateLs= sSupplierRcRelateService.getSupplierRcRelateBySuppliersId(transferRequestVO.getSupplierId());
//            for(SSupplierRcRelate sSupplierRcRelate:sSupplierRcRelateLs){
//                sSupplierRcRelate.setSupplierStatus(Integer.valueOf(SupplierStatusEnum.TURN_TO_PENDING_WATCH.getCode()));
//            }
//            sSupplierRcRelateService.updateBatchById(sSupplierRcRelateLs);
            SessionUserVo currentUserVo = UserUtils.getCurrentUserVo();
            if (currentUserVo == null) {
                throw new RuntimeException("未获取到当前操作人信息，请登录后重试");
            }
            String userId = currentUserVo.getEmployeeID();
            //审批历程
            //Step: 审批历史记录更新
            SHistoryComment sHistoryComment = new SHistoryComment();

            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
            sHistoryComment.setRelatedId(sSupplierRcRelate.getSuppliersId());
            sHistoryComment.setSubRelatedId(sSupplierRcRelate.getId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.QUALIFIED_TURN_TO_PENDING_WATCH_NODE_NAME.getCode()));
            sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.QUALIFIED_TURN_TO_PENDING_WATCH_CONTENT.getCode()));

            sHistoryComment.setActionName(ActionTypeEnum.TURN_TO_PENDING_WATCH.getDesc());
            sHistoryComment.setBaseFeilds(userId, null, 0, true);
            sHistoryCommentService.saveSHistoryComment(sHistoryComment);

            //MBS流程审批
            Map<String, Object> mapParams = new HashMap<String, Object>();
            mapParams.put("CURRENT_USER_ID", userId);
            mapParams.put("CURRENT_USER_NAME", currentUserVo.getUserName());
            mapParams.put("CURRENT_DEPT_CODE", currentUserVo.getDept());
            mapParams.put("RELATE_ID", transferRequestVO.getSupplierId());
            mapParams.put("SUB_RELATE_ID", transferRequestVO.getRcRelatedId());

            mapParams.put("ORG_CODE", currentUserVo.getCompanyCode());
            mapParams.put("ORG_NAME", currentUserVo.getsCompanyName());
            mapParams.put("EMPLOYEE_CODE", currentUserVo.getEmployeeID());

//          mapParams.get("CURRENT_USER_ID")
//          mapParams.get("RELATE_ID")
//          mapParams.get("ORG_CODE")
//          mapParams.get("ORG_NAME")
//          mapParams.get("EMPLOYEE_CODE")
            Map<String, Object> mapBpmParams = bpmUtil.invokeApprovalFlow(mapParams, AbutmentSubTypeEnum.TURN_TO_PENDING_WATCH_APPROVE.getCode());
            Boolean isSuccess = (Boolean) mapBpmParams.get("IS_SUCCESS");
            String mbsUrl = (String) mapBpmParams.get("MBS_URL");
            if (isSuccess == false) {
                throw new RuntimeException("BPM转待观察审核对接失败");
            } else {
                SHistoryComment updateSHistoryComment = new SHistoryComment();
                updateSHistoryComment.setId(sHistoryComment.getId());
                updateSHistoryComment.setCommentUrl(mbsUrl);
                sHistoryCommentService.updateById(updateSHistoryComment);
            }


            restReturnResult = restReturnResult.success();

            return restReturnResult;
        } catch (NullPointerException e) {
            e.printStackTrace();
            logger.info("----------------turnToPendingWatch-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> turnToUnqualified(TransferRequestVO transferRequestVO) throws RuntimeException {
        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        try {
            String subSupplierId = transferRequestVO.getRcRelatedId();

            if (StringUtils.isEmpty(subSupplierId)) {
                throw new RuntimeException("id为空");
            }
            SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(subSupplierId);
            if (sSupplierRcRelate == null) {
                throw new RuntimeException("供方数据不存在");
            }
            if (!SupplierStatusEnum.QUALIFIED.getCode().equals(sSupplierRcRelate.getSupplierStatus() + "")) {
                throw new RuntimeException("只有合格供方可以转不合格");
            }
            sSupplierRcRelate.setSupplierStatus(Integer.valueOf(SupplierStatusEnum.TURN_TO_UNQUALIFIED.getCode()));
            sSupplierRcRelate.setUnqualifiedTime(new Date());
            sSupplierRcRelate.setTurnToUnqualifiedDesc(transferRequestVO.getRemarks());
            sSupplierRcRelateService.updateById(sSupplierRcRelate);
            SessionUserVo currentUserVo = UserUtils.getCurrentUserVo();
            if (currentUserVo == null) {
                throw new RuntimeException("未获取到当前操作人信息，请登录后重试");
            }
            String userId = currentUserVo.getEmployeeID();
            //审批历程
            //Step: 审批历史记录更新
            SHistoryComment sHistoryComment = new SHistoryComment();

            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
            sHistoryComment.setRelatedId(sSupplierRcRelate.getSuppliersId());
            sHistoryComment.setSubRelatedId(sSupplierRcRelate.getId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.QUALIFIED_TURN_TO_UNQUALIFIED_NODE_NAME.getCode()));
            sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.QUALIFIED_TURN_TO_UNQUALIFIED_COMMENT_CONTENT.getCode()));

            sHistoryComment.setActionName(ActionTypeEnum.TURN_TO_UNQUALIFIED.getDesc());
            sHistoryComment.setBaseFeilds(userId, null, 0, true);
            sHistoryCommentService.saveSHistoryComment(sHistoryComment);

            LicenseUtil.INSTANCE.validate();
            //MBS流程审批
            Map<String, Object> mapParams = new HashMap<String, Object>();
            mapParams.put("CURRENT_USER_ID", userId);
            mapParams.put("CURRENT_USER_NAME", currentUserVo.getUserName());
            mapParams.put("CURRENT_DEPT_CODE", currentUserVo.getDept());
            mapParams.put("RELATE_ID", transferRequestVO.getSupplierId());
            mapParams.put("SUB_RELATE_ID", transferRequestVO.getRcRelatedId());

            mapParams.put("ORG_CODE", currentUserVo.getCompanyCode());
            mapParams.put("ORG_NAME", currentUserVo.getsCompanyName());
            mapParams.put("EMPLOYEE_CODE", currentUserVo.getEmployeeID());

//          mapParams.get("CURRENT_USER_ID")
//          mapParams.get("RELATE_ID")
//          mapParams.get("ORG_CODE")
//          mapParams.get("ORG_NAME")
//          mapParams.get("EMPLOYEE_CODE")
            Map<String, Object> mapBpmParams = bpmUtil.invokeApprovalFlow(mapParams, AbutmentSubTypeEnum.TURN_TO_UNQUALIFIED_APPROVE.getCode());
            Boolean isSuccess = (Boolean) mapBpmParams.get("IS_SUCCESS");
            String mbsUrl = (String) mapBpmParams.get("MBS_URL");
            if (isSuccess == false) {
                throw new RuntimeException("BPM转不合格审核对接失败");
            } else {
                SHistoryComment updateSHistoryComment = new SHistoryComment();
                updateSHistoryComment.setId(sHistoryComment.getId());
                updateSHistoryComment.setCommentUrl(mbsUrl);
                sHistoryCommentService.updateById(updateSHistoryComment);
            }


            restReturnResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, mbsUrl, null, "操作成功");

            return restReturnResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------turnToUnqualified-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> turnToPotential(TransferRequestVO transferRequestVO) throws RuntimeException {
        RestReturnResult<Object> restReturnResult = RestReturnResult.error();
        SHistoryComment sHistoryComment = null;
        try {
            String ITEM_KIND_CODE = "";

            SessionUserVo currentUserVo = UserUtils.getCurrentUserVo();
            if (currentUserVo == null) {
                throw new RuntimeException("未获取到当前操作人信息，请登录后重试");
            }
            LicenseUtil.INSTANCE.validate();
            String userId = currentUserVo.getEmployeeID();
            if (transferRequestVO.getActionType() != null && transferRequestVO.getActionType() == 1) {
                String supplierId = transferRequestVO.getSupplierId();
                if (StringUtils.isEmpty(supplierId)) {
                    throw new RuntimeException("供方id为空");
                }
                SSuppliers sSuppliers = sSuppliersService.selectById(supplierId);
                if (sSuppliers == null) {
                    throw new RuntimeException("供方数据不存在");
                }
                if (!SupplierStatusEnum.BLACK_LIBRARYS.getCode().equals(sSuppliers.getSupplierStatus() + "")) {
                    throw new RuntimeException("只有不合格或黑库供方可以转潜在");
                }
                String supplierCategoryIds = sSuppliers.getSupplierCategoryIds();
                if (StringUtils.isNotEmpty(supplierCategoryIds) && StringUtils.isEmpty(ITEM_KIND_CODE)) {
//                    String categoryId=supplierCategoryIds.split(",")[0];
//                    SSuppliersCategory sSuppliersCategory=sSuppliersCategoryService.selectById(categoryId);
//                    if(sSuppliersCategory!=null&&StringUtils.isNotEmpty(sSuppliersCategory.getCategoryCode())){
//                        ITEM_KIND_CODE=sSuppliersCategory.getCategoryCode();
//                    }
                    String[] categoryIds = supplierCategoryIds.split(",");
                    List<String> categoryIdList = Arrays.asList(categoryIds);
                    List<SSuppliersCategory> sSuppliersCategoryList = sSuppliersCategoryService.selectBatchIds(categoryIdList);
                    if (sSuppliersCategoryList != null && sSuppliersCategoryList.size() > 0) {
                        for (SSuppliersCategory sSuppliersCategory : sSuppliersCategoryList) {
                            String categoryCode = sSuppliersCategory.getCategoryCode();
                            if (categoryCode.indexOf("A") > 0) {
                                ITEM_KIND_CODE = categoryCode;
                                break;
                            }
                        }

                        if (StringUtils.isBlank(ITEM_KIND_CODE)) {
                            ITEM_KIND_CODE = sSuppliersCategoryList.get(0).getCategoryCode();
                        }
                    }
                }

                sSuppliers.setTurnToPotentialDesc(transferRequestVO.getRemarks());
                sSuppliers.setTurnToPotentialTime(new Date());
                sSuppliers.setSupplierStatus(Integer.valueOf(SupplierStatusEnum.TURN_TO_POTENTIAL.getCode()));
                sSuppliersService.updateById(sSuppliers);

                List<SSupplierRcRelate> sSupplierRcRelateLs = sSupplierRcRelateService.getSupplierRcRelateBySuppliersId(supplierId);
                for (SSupplierRcRelate sSupplierRcRelate : sSupplierRcRelateLs) {
                    sSupplierRcRelate.setSupplierStatus(Integer.valueOf(SupplierStatusEnum.TURN_TO_POTENTIAL.getCode()));
                }
                sSupplierRcRelateService.updateBatchById(sSupplierRcRelateLs);

                //审批历程
                //Step: 审批历史记录更新
                sHistoryComment = new SHistoryComment();

                sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
                sHistoryComment.setRelatedId(supplierId);
                sHistoryComment.setSubRelatedId(supplierId);
                sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
                if (sSuppliers.getSupplierBigStatus() == SupplierBigStatusEnum.BLACK_LIBRARY.getCode()) {
                    sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.BLACK_LIBRARY_TURN_TO_POTENTIAL_NODE_NAME.getCode()));
                    sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.BLACK_LIBRARY_TURN_TO_POTENTIAL_COMMENT_CONTENT.getCode()));
                }
                sHistoryComment.setActionName(ActionTypeEnum.TURN_TO_POTENTIAL.getDesc());
                sHistoryComment.setBaseFeilds(userId, null, 0, true);
                sHistoryCommentService.saveSHistoryComment(sHistoryComment);
            } else {
                String subSupplierId = transferRequestVO.getRcRelatedId();
                if (StringUtils.isEmpty(subSupplierId)) {
                    throw new RuntimeException("id为空");
                }
                SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(subSupplierId);
                if (sSupplierRcRelate == null) {
                    throw new RuntimeException("供方数据不存在");
                }
                if (!SupplierStatusEnum.UNQUALIFIED.getCode().equals(sSupplierRcRelate.getSupplierStatus() + "")) {
                    throw new RuntimeException("只有不合格或黑库供方可以转潜在");
                }
                String supplierCategoryActualIds = sSupplierRcRelate.getSupplierCategoryActualIds();
                String supplierCategoryIds = sSupplierRcRelate.getSupplierCategoryIds();
                if (StringUtils.isNotEmpty(supplierCategoryActualIds)) {
//                    String categoryId=supplierCategoryActualIds.split(",")[0];
//                    SSuppliersCategory sSuppliersCategory=sSuppliersCategoryService.selectById(categoryId);
//                    if(sSuppliersCategory!=null&&StringUtils.isNotEmpty(sSuppliersCategory.getCategoryCode())){
//                        ITEM_KIND_CODE=sSuppliersCategory.getCategoryCode();
//                    }

                    String[] categoryIds = supplierCategoryActualIds.split(",");
                    List<String> categoryIdList = Arrays.asList(categoryIds);
                    List<SSuppliersCategory> sSuppliersCategoryList = sSuppliersCategoryService.selectBatchIds(categoryIdList);
                    if (sSuppliersCategoryList != null && sSuppliersCategoryList.size() > 0) {
                        for (SSuppliersCategory sSuppliersCategory : sSuppliersCategoryList) {
                            String categoryCode = sSuppliersCategory.getCategoryCode();
                            if (categoryCode.indexOf("A") > 0) {
                                ITEM_KIND_CODE = categoryCode;
                                break;
                            }
                        }

                        if (StringUtils.isBlank(ITEM_KIND_CODE)) {
                            ITEM_KIND_CODE = sSuppliersCategoryList.get(0).getCategoryCode();
                        }
                    }
                } else if (StringUtils.isNotEmpty(supplierCategoryIds) && StringUtils.isEmpty(ITEM_KIND_CODE)) {
//                    String categoryId=supplierCategoryIds.split(",")[0];
//                    SSuppliersCategory sSuppliersCategory=sSuppliersCategoryService.selectById(categoryId);
//                    if(sSuppliersCategory!=null&&StringUtils.isNotEmpty(sSuppliersCategory.getCategoryCode())){
//                        ITEM_KIND_CODE=sSuppliersCategory.getCategoryCode();
//                    }
                    String[] categoryIds = supplierCategoryIds.split(",");
                    List<String> categoryIdList = Arrays.asList(categoryIds);
                    List<SSuppliersCategory> sSuppliersCategoryList = sSuppliersCategoryService.selectBatchIds(categoryIdList);
                    if (sSuppliersCategoryList != null && sSuppliersCategoryList.size() > 0) {
                        for (SSuppliersCategory sSuppliersCategory : sSuppliersCategoryList) {
                            String categoryCode = sSuppliersCategory.getCategoryCode();
                            if (categoryCode.indexOf("A") > 0) {
                                ITEM_KIND_CODE = categoryCode;
                                break;
                            }
                        }

                        if (StringUtils.isBlank(ITEM_KIND_CODE)) {
                            ITEM_KIND_CODE = sSuppliersCategoryList.get(0).getCategoryCode();
                        }
                    }
                }
                sSupplierRcRelate.setTurnToPotentialDesc(transferRequestVO.getRemarks());
                sSupplierRcRelate.setTurnToPotentialTime(new Date());
                sSupplierRcRelate.setSupplierStatus(Integer.valueOf(SupplierStatusEnum.TURN_TO_POTENTIAL.getCode()));
                sSupplierRcRelateService.updateById(sSupplierRcRelate);

                //审批历程
                //Step: 审批历史记录更新
                sHistoryComment = new SHistoryComment();

                sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
                sHistoryComment.setRelatedId(sSupplierRcRelate.getSuppliersId());
                sHistoryComment.setSubRelatedId(sSupplierRcRelate.getId());
                sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
                if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.UNQUALIFIED.getCode()) {
                    sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.UNQUALIFIED_TURN_TO_POTENTIAL_NODE_NAME.getCode()));
                    sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.UNQUALIFIED_TURN_TO_POTENTIAL_COMMENT_CONTENT.getCode()));
                }
                sHistoryComment.setActionName(ActionTypeEnum.TURN_TO_POTENTIAL.getDesc());
                sHistoryComment.setBaseFeilds(userId, null, 0, true);
                sHistoryCommentService.saveSHistoryComment(sHistoryComment);
            }


            //MBS流程审批

            Map<String, Object> mapParams = new HashMap<String, Object>();

            mapParams.put("RELATE_ID", transferRequestVO.getSupplierId());
            mapParams.put("SUB_RELATE_ID", transferRequestVO.getRcRelatedId());
            mapParams.put("ITEM_KIND_CODE", ITEM_KIND_CODE);
            mapParams.put("CURRENT_USER_ID", currentUserVo.getEmployeeID());
            mapParams.put("CURRENT_USER_NAME", currentUserVo.getUserName());
            mapParams.put("ORG_CODE", currentUserVo.getCompanyCode());
            mapParams.put("ORG_NAME", currentUserVo.getsCompanyName());
            mapParams.put("EMPLOYEE_CODE", currentUserVo.getEmployeeID());

//          mapParams.get("CURRENT_USER_ID")
//          mapParams.get("RELATE_ID")
//          mapParams.get("ORG_CODE")
//          mapParams.get("ORG_NAME")
//          mapParams.get("EMPLOYEE_CODE")
            Map<String, Object> mapBpmParams = bpmUtil.invokeApprovalFlow(mapParams, AbutmentSubTypeEnum.TURN_TO_POTENTIAL_APPROVE.getCode());
            Boolean isSuccess = (Boolean) mapBpmParams.get("IS_SUCCESS");
            String mbsUrl = (String) mapBpmParams.get("MBS_URL");
            if (isSuccess == false) {
                throw new RuntimeException("BPM转潜在审核对接失败");
            } else {
                SHistoryComment updateSHistoryComment = new SHistoryComment();
                updateSHistoryComment.setId(sHistoryComment.getId());
                updateSHistoryComment.setCommentUrl(mbsUrl);
                sHistoryCommentService.updateById(updateSHistoryComment);
            }


            restReturnResult = restReturnResult.success();

            return restReturnResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------turnToUnqualified-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> turnToBlackLibrary(TransferRequestVO transferRequestVO) throws RuntimeException {
        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        LicenseUtil.INSTANCE.validate();
        try {
            String supplierId = transferRequestVO.getSupplierId();
            if (StringUtils.isEmpty(supplierId)) {
                throw new RuntimeException("供方id为空");
            }
            SSuppliers sSuppliers = sSuppliersService.selectById(supplierId);
            if (sSuppliers == null) {
                throw new RuntimeException("供方数据不存在");
            }
            if (SupplierStatusEnum.TURN_TO_BLACK_LIBRARY.getCode().equals(sSuppliers.getSupplierStatus() + "")) {
                throw new RuntimeException("有其他地区公司正在转黑库");
            }
            SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(transferRequestVO.getRcRelatedId());
            if (!(SupplierStatusEnum.QUALIFIED.getCode().equals(sSupplierRcRelate.getSupplierStatus() + "") ||
                    SupplierStatusEnum.UNQUALIFIED.getCode().equals(sSupplierRcRelate.getSupplierStatus() + ""))) {
                throw new RuntimeException("只有合格或不合格供方可以转黑库");
            }
            sSuppliers.setTurnToBlackLibraryDesc(transferRequestVO.getRemarks());
            sSuppliers.setTurnToBlackLibraryTime(new Date());
            sSuppliers.setSupplierStatus(Integer.valueOf(SupplierStatusEnum.TURN_TO_BLACK_LIBRARY.getCode()));
            sSuppliersService.updateById(sSuppliers);
            SessionUserVo currentUserVo = UserUtils.getCurrentUserVo();
            if (currentUserVo == null) {
                throw new RuntimeException("未获取到当前操作人信息，请登录后重试");
            }
            String userId = currentUserVo.getEmployeeID();
            sSupplierRcRelate.setSupplierStatus(Integer.valueOf(SupplierStatusEnum.TURN_TO_BLACK_LIBRARY.getCode()));
            sSupplierRcRelate.setTurnToBlackLibraryDesc(transferRequestVO.getRemarks());
            sSupplierRcRelate.setTurnToBlackLibraryTime(new Date());
            sSupplierRcRelateService.updateById(sSupplierRcRelate);

//            List<SSupplierRcRelate>  sSupplierRcRelateLs= sSupplierRcRelateService.getSupplierRcRelateBySuppliersId(supplierId);
//            for(SSupplierRcRelate obj:sSupplierRcRelateLs){
//                obj.setSupplierStatus(Integer.valueOf(SupplierStatusEnum.TURN_TO_BLACK_LIBRARY.getCode()));
//                obj.setTurnToBlackLibraryDesc(transferRequestVO.getRemarks());
//                obj.setTurnToBlackLibraryTime(new Date());
//            }
//            sSupplierRcRelateService.updateBatchById(sSupplierRcRelateLs);

            //审批历程
            //Step: 审批历史记录更新
            SHistoryComment sHistoryComment = new SHistoryComment();

            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
            sHistoryComment.setRelatedId(sSupplierRcRelate.getSuppliersId());
            sHistoryComment.setSubRelatedId(sSupplierRcRelate.getId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.QUALIFIED.getCode()) {
                sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.QUALIFIED_TURN_TO_BLACK_LIBRARY_NODE_NAME.getCode()));
                sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.QUALIFIED_TURN_TO_BLACK_LIBRARY_COMMENT_CONTENT.getCode()));
            } else if (sSupplierRcRelate.getSupplierBigStatus() == SupplierBigStatusEnum.UNQUALIFIED.getCode()) {
                sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.UNQUALIFIED_TURN_TO_BLACK_LIBRARY_NODE_NAME.getCode()));
                sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.UNQUALIFIED_TURN_TO_BLACK_LIBRARY_COMMENT_CONTENT.getCode()));
            }

            sHistoryComment.setActionName(ActionTypeEnum.TURN_TO_BLACK_LIBRARY.getDesc());
            sHistoryComment.setBaseFeilds(userId, null, 0, true);
            sHistoryCommentService.saveSHistoryComment(sHistoryComment);

            //MBS流程审批
            Map<String, Object> mapParams = new HashMap<String, Object>();
            mapParams.put("CURRENT_USER_ID", userId);
            mapParams.put("CURRENT_USER_NAME", currentUserVo.getUserName());
            mapParams.put("RELATE_ID", transferRequestVO.getSupplierId());
            mapParams.put("SUB_RELATE_ID", transferRequestVO.getRcRelatedId());

            mapParams.put("ORG_CODE", currentUserVo.getCompanyCode());
            mapParams.put("ORG_NAME", currentUserVo.getsCompanyName());
            mapParams.put("EMPLOYEE_CODE", currentUserVo.getEmployeeID());

//          mapParams.get("CURRENT_USER_ID")
//          mapParams.get("RELATE_ID")
//          mapParams.get("ORG_CODE")
//          mapParams.get("ORG_NAME")
//          mapParams.get("EMPLOYEE_CODE")
            Map<String, Object> mapBpmParams = bpmUtil.invokeApprovalFlow(mapParams, AbutmentSubTypeEnum.TURN_TO_BLACK_LIBRARY_APPROVE.getCode());
            Boolean isSuccess = (Boolean) mapBpmParams.get("IS_SUCCESS");
            String mbsUrl = (String) mapBpmParams.get("MBS_URL");
            if (isSuccess == false) {
                throw new RuntimeException("BPM转黑库审核对接失败");
            } else {
                SHistoryComment updateSHistoryComment = new SHistoryComment();
                updateSHistoryComment.setId(sHistoryComment.getId());
                updateSHistoryComment.setCommentUrl(mbsUrl);
                sHistoryCommentService.updateById(updateSHistoryComment);
            }

            restReturnResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, mbsUrl, null, "操作成功");

            return restReturnResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------turnToUnqualified-----e---------:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 重新考察
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult<Object> reDoInspection(String rcRelatedId) throws RuntimeException {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        LicenseUtil.INSTANCE.validate();
        try {

            if (StringUtils.isNotEmpty(rcRelatedId)) {
                SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(rcRelatedId);
                if (sSupplierRcRelate != null) {
                    sSupplierRcRelate.setSupplierStatus(NumberUtils.toInteger("" + SupplierStatusEnum.SITE_INSPECTION.getCode()));
                    sSupplierRcRelate.setSupplierBigStatus(SupplierBigStatusEnum.POTENTIAL.getCode());

                    sSupplierRcRelateService.updateById(sSupplierRcRelate);

                    //添加待办
//					SSuppliersInspection sSuppliersInspection = sSuppliersInspectionService.getLatestRecordBySuppliersIdAndRegionalCompanyId(
//							sSupplierRcRelate.getSuppliersId(), sSupplierRcRelate.getRegionalCompanyId());

                    SSuppliers sSuppliers = sSuppliersService.selectById(sSupplierRcRelate.getSuppliersId());

                    if (sSuppliers != null) {
                        String userId = UserUtils.getCurrentUserId();
                        String titleTemplate = sCommentConfigService.getValueByCode(CommentConfigEnum.MY_DEAL_TEMPLATE.getCode());
                        String title = MessageFormat.format(titleTemplate, MyDealSubTypeEnum.SITE_INSPECTION.getDesc(), sSuppliers.getCompanyName());

                        sMyDealsService.dealMyDeals(sSupplierRcRelate.getSuppliersId(), rcRelatedId, DealTypeEnum.SUPPLIERS.getCode(), new String[]{userId},
                                MyDealSubTypeEnum.SITE_INSPECTION.getCode(), MyDealActionTypeEnum.SITE_INSPECTION.getCode(),
                                title, userId, true, null);

                        restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS);
                    } else {
                        restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
                    }

                } else {
                    restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
                }
            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------reDoInspection-----e---------:" + e.getMessage());
            throw new RuntimeException(e);
        }

        return restResult;
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult checkDoSiteInspectionInQualificationList(
            CheckDoSiteInspectionRequestVO checkDoSiteInspectionRequestVO) throws RuntimeException {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        LicenseUtil.INSTANCE.validate();
        try {

            if (checkDoSiteInspectionRequestVO != null
                    && StringUtils.isNotBlank(checkDoSiteInspectionRequestVO.getSupplierId())
                    && StringUtils.isNotBlank(checkDoSiteInspectionRequestVO.getServiceRegionalCompanyId())) {

                SSuppliersInspection sSuppliersInspection = sSuppliersInspectionService.getUnDoneSuppliersInspectionBySupplierIdAndRegionCompanyId(
                        checkDoSiteInspectionRequestVO.getSupplierId(), checkDoSiteInspectionRequestVO.getServiceRegionalCompanyId());

                if (sSuppliersInspection != null) {
                    restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, false);
                } else {
                    restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, true);
                }

            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("----------------checkDoSiteInspectionInQualificationList-----e---------:" + e.getMessage());
            throw new RuntimeException(e);
        }

        return restResult;
    }

    /**
     * 审核现场考察申请
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult checkSuppliersInspectionApply(SuppliersInspectionRequestVO suppliersInspectionRequestVO) {

        try {

            String userId = UserUtils.getCurrentUserId();

            SSupplierRcRelate sSupplierRcRelate = sSupplierRcRelateService.selectById(suppliersInspectionRequestVO.getRcRelatedId());
            if (sSupplierRcRelate == null) {
                throw new RuntimeException("地区公司关联供方记录不存在", new ServiceThrowable());
            }

            suppliersInspectionRequestVO.setSuppliersId(sSupplierRcRelate.getSuppliersId());
            suppliersInspectionRequestVO.setRegionalCompanyId(sSupplierRcRelate.getRegionalCompanyId());

            boolean workflowFlag = this.checkSiteInspectionByWorkflow(suppliersInspectionRequestVO.getRcRelatedId());

            //供应商基本情况及地区公司关联表相关状态变更
            SuppliersAuditRequestVO suppliersAuditRequestVO = new SuppliersAuditRequestVO();
            suppliersAuditRequestVO.setId(suppliersInspectionRequestVO.getSuppliersId());
            suppliersAuditRequestVO.setRcRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
            suppliersAuditRequestVO.setActionType(suppliersInspectionRequestVO.getActionType());

            if (workflowFlag) {
                this.updateSupplierStatusNonMBS(suppliersAuditRequestVO);
            }

            SSuppliersInspection sSuppliersInspection = sSuppliersInspectionService.getLatestRecordBySuppliersIdAndRegionalCompanyId(suppliersInspectionRequestVO.getSuppliersId(), sSupplierRcRelate.getRegionalCompanyId());


            //Step 3: 添加待办已办记录
            SSuppliers sSuppliers = sSuppliersService.selectById(suppliersInspectionRequestVO.getSuppliersId());

            String titleTemplate = sCommentConfigService.getValueByCode(CommentConfigEnum.MY_DEAL_TEMPLATE.getCode());
            String title = "";

            if (suppliersInspectionRequestVO.getActionType() == ActionTypeEnum.REFUSE_SITE_INSPECTION.getCode()) {

                if (sSuppliers != null) {
                    title = MessageFormat.format(titleTemplate, MyDealSubTypeEnum.SITE_INSPECTION.getDesc(), sSuppliers.getCompanyName()/* + MyDealSubTypeEnum.SITE_INSPECTION.getDesc()*/);
                }


                sMyDealsService.dealMyDeals(suppliersAuditRequestVO.getId(), suppliersAuditRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(),
                        new String[]{sSuppliersInspection.getCreateBy()}, MyDealSubTypeEnum.SITE_INSPECTION.getCode(), MyDealActionTypeEnum.SITE_INSPECTION.getCode(),
                        title, userId, false, suppliersInspectionRequestVO.getThirdRelatedId());

                //更新actionType
                if (sSupplierRcRelate != null) {
                    sSupplierRcRelate.setActionType(MyDealActionTypeEnum.SITE_INSPECTION.getCode());

                    sSupplierRcRelateService.updateById(sSupplierRcRelate);
                }


            } else if (suppliersInspectionRequestVO.getActionType() == ActionTypeEnum.AGREE_SITE_INSPECTION.getCode()) {

                InspectionBaseInfoResponseVO inspectionBaseInfo = this.getInspectionBaseInfo(suppliersInspectionRequestVO.getSuppliersId(), suppliersInspectionRequestVO.getRcRelatedId());

                if (sSuppliers != null) {
                    title = MessageFormat.format(titleTemplate, MyDealSubTypeEnum.SITE_INSPECTION.getDesc(), sSuppliers.getCompanyName() + sCommentConfigService.getValueByCode(CommentConfigEnum.SITE_INSPECTION_LEADER_AUDIT_TITLE.getCode()));
                }

                sMyDealsService.dealMyDeals(suppliersInspectionRequestVO.getSuppliersId(), suppliersInspectionRequestVO.getRcRelatedId(), DealTypeEnum.SUPPLIERS.getCode(), new String[]{inspectionBaseInfo.getInspectionLeaderUserId()},
                        MyDealSubTypeEnum.SITE_INSPECTION.getCode(), MyDealActionTypeEnum.LEADER_AUDIT_SITE_INSPECTION.getCode(),
                        title, userId, false, suppliersInspectionRequestVO.getThirdRelatedId());

                //更新actionType
                if (sSupplierRcRelate != null) {
                    sSupplierRcRelate.setActionType(MyDealActionTypeEnum.LEADER_AUDIT_SITE_INSPECTION.getCode());
                    sSupplierRcRelate.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);

                    sSupplierRcRelateService.updateById(sSupplierRcRelate);
                }

            }


            //Step2: 审批历史记录更新
            SHistoryComment sHistoryComment = new SHistoryComment();

            sHistoryComment.setModelType(HistoryCommentModelTypeEnum.AUDIT_PROCESS_SUPPLIERS_INFO.getCode()); //供方信息审核历程
            sHistoryComment.setRelatedId(suppliersInspectionRequestVO.getSuppliersId());
            sHistoryComment.setSubRelatedId(suppliersInspectionRequestVO.getRcRelatedId());
            sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
            sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.CHECK_SITE_INSPECTION_APPLY_NODE_NAME.getCode()));
            //sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.CHECK_SITE_INSPECTION_APPLY_COMMENT_CONTENT.getCode()));


            //Action: 52：同意，53：拒绝
            sHistoryComment.setActionName(ActionTypeEnumUtil.actionTypeEnumMap.get(suppliersInspectionRequestVO.getActionType()));
            if (ActionTypeEnum.AGREE_SITE_INSPECTION.getCode() == suppliersInspectionRequestVO.getActionType()) {
                sHistoryComment.setAgreeFlag(CommonConstants.AGREE_FLAG);
//                sSuppliersInspection.setDoneFlag(CommonConstants.YES_INTEGER);
                sSuppliersInspection.setGroupUserDoneFlag(CommonConstants.YES_INTEGER);
                sSuppliersInspection.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);
                sSuppliersInspectionService.updateById(sSuppliersInspection);

                SMessages message = sMessagesService.selectById(suppliersInspectionRequestVO.getThirdRelatedId());
                if (message == null) {
                    throw new RuntimeException("考察公告不存在", new ServiceThrowable());
                }
                message.setShowFlag(CommonConstants.YES_INTEGER);
                if (StringUtils.isEmpty(sSuppliersInspection.getInspectionAnnounceUserIds())) {//所有人公示
                    sMessagesService.updateById(message);
                } else {
                    //给选中的人发公告
                    for (String annoId : sSuppliersInspection.getInspectionAnnounceUserIds().split(",")) {
                        if (annoId.equals(sSuppliersInspection.getInspectionGroupUserIds())) {
                            continue;
                        }
                        message.setUserIds(annoId);
                        message.setId(null);
                        message.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
                        sMessagesService.insert(message);
                    }

                    message.setUserIds(sSuppliersInspection.getInspectionGroupUserIds());
                    message.setId(null);
                    message.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
                    sMessagesService.insert(message);
                }


            } else if (ActionTypeEnum.REFUSE_SITE_INSPECTION.getCode() == suppliersInspectionRequestVO.getActionType()) {
                sHistoryComment.setAgreeFlag(CommonConstants.NO_AGREE_FLAG);
//                sSuppliersInspection.setDoneFlag(CommonConstants.NO_INTEGER);
                sSuppliersInspection.setGroupUserDoneFlag(CommonConstants.YES_INTEGER);
                sSuppliersInspection.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);
                sSuppliersInspectionService.updateById(sSuppliersInspection);

            }

            LicenseUtil.INSTANCE.validate();
            sHistoryCommentService.saveSHistoryComment(sHistoryComment);

            return new RestReturnResult(CommonConstants.SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }

    @Override
    public List<SSuppliersLastThreeAchieve> getOutContactSimList(String name, String supplierId) {
        return sSuppliersLastThreeAchieveService.findOutSimListByName(name, supplierId);
    }


    @Override
    public void deleteSupplierInspectionPerformById(String id) {
        SSuppliersInspectionPerform sSuppliersInspectionPerform = new SSuppliersInspectionPerform();
        sSuppliersInspectionPerform.setId(id);
        sSuppliersInspectionPerform.setDelFlag(CommonConstants.DEL_FLAG_DELETE);
        sSuppliersInspectionPerformService.updateById(sSuppliersInspectionPerform);
    }

    @Override
    public void addSuppliersInspectionPerform(SSuppliersInspectionPerform sSuppliersInspectionPerform) {
        sSuppliersInspectionPerform.setBaseFeilds(UserUtils.getCurrentUserId(), "", CommonConstants.DEL_FLAG_NORMAL, true);
        sSuppliersInspectionPerformService.insert(sSuppliersInspectionPerform);
    }

    @Override
    public SuppliersInspectionDetailVO selectSupplierInspectionDetail(String id) {
        SuppliersInspectionDetailVO suppliersInspectionDetailVO = new SuppliersInspectionDetailVO();
        //List<ExtSSuppliersInspectionTmpl> list = sSuppliersInspectionTmplService.selectParentAndChildsByCId("1x");
        SSuppliersInspection sSuppliersInspection = sSuppliersInspectionService.selectById(id);
        suppliersInspectionDetailVO.setSSuppliersInspection(sSuppliersInspection);

        SSuppliers sSuppliers = sSuppliersService.selectById(sSuppliersInspection.getSuppliersId());
        suppliersInspectionDetailVO.setSupplierServiceCategoryIds(sSuppliers.getSupplierServiceCategoryIds());
        String[] s = {sSuppliers.getSupplierServiceCategoryIds()};
        suppliersInspectionDetailVO.setSupplierServiceCategoryNames(sSuppliersCategoryService.getSupplierCategoryNames(s));
        suppliersInspectionDetailVO.setSupplierName(sSuppliers.getCompanyName());
        suppliersInspectionDetailVO.setIntentionsupplierCategoryNames(sSuppliersCategoryService.getSupplierCategoryNames(sSuppliersInspection.getSupplierCategoryIds().split(",")));
        suppliersInspectionDetailVO.setInspectionLeaderUserNames(sysUserService.getSysUserNameByIds(sSuppliersInspection.getInspectionLeaderUserId()));
        suppliersInspectionDetailVO.setInspectionMemberUserNames(sysUserService.getSysUserNameByIds(sSuppliersInspection.getInspectionMemberUserIds()));
        SRegionalCompany sRegionalCompany = sRegionalCompanyService.selectById(sSuppliersInspection.getRegionalCompanyId());
        if (sRegionalCompany != null) {
            suppliersInspectionDetailVO.setIntentionRegionalCompanyNames(sRegionalCompany.getRegionalCompanyName());
        }
        List<SSuppliersInspectionPerform> sSuppliersInspectionPerforms = sSuppliersInspectionPerformService.selectByInspectId(id);
        suppliersInspectionDetailVO.setSSuppliersInspectionPerforms(sSuppliersInspectionPerforms);

        SSuppliersInspectionAc sSuppliersInspectionAc = sSuppliersInspectionAcService.selectByInspectId(id);
        List<ExtSSuppliersInspectionItems> extSSuppliersInspectionItems = null;
        if (sSuppliersInspectionAc != null) {//修改
            suppliersInspectionDetailVO.setSSuppliersInspectionAc(sSuppliersInspectionAc);
            suppliersInspectionDetailVO.setSAttachments1(sAttachmentService.getByFormIdAndAttachmentType(id, AttachmentTypeEnum.ATTACHMENT_TYPE_61.getCode(), null));
            suppliersInspectionDetailVO.setSAttachments2(sAttachmentService.getByFormIdAndAttachmentType(id, AttachmentTypeEnum.ATTACHMENT_TYPE_62.getCode(), null));
            suppliersInspectionDetailVO.setSAttachments3(sAttachmentService.getByFormIdAndAttachmentType(id, AttachmentTypeEnum.ATTACHMENT_TYPE_63.getCode(), null));
            suppliersInspectionDetailVO.setSAttachments4(sAttachmentService.getByFormIdAndAttachmentType(id, AttachmentTypeEnum.ATTACHMENT_TYPE_64.getCode(), null));
            suppliersInspectionDetailVO.setSAttachments5(sAttachmentService.getByFormIdAndAttachmentType(id, AttachmentTypeEnum.ATTACHMENT_TYPE_65.getCode(), null));
            suppliersInspectionDetailVO.setSAttachments6(sAttachmentService.getByFormIdAndAttachmentType(id, AttachmentTypeEnum.ATTACHMENT_TYPE_66.getCode(), null));
            suppliersInspectionDetailVO.setSAttachments7(sAttachmentService.getByFormIdAndAttachmentType(id, AttachmentTypeEnum.ATTACHMENT_TYPE_67.getCode(), null));
            extSSuppliersInspectionItems = sSuppliersInspectionItemsService.getParentAndChildsByInspectId(id);
        } else {
            List<ExtSSuppliersInspectionTmpl> list = sSuppliersInspectionTmplService.selectParentAndChildsByCId(sSuppliers.getSupplierServiceCategoryIds());
            extSSuppliersInspectionItems = Lists.newArrayListWithCapacity(list.size());
            try {
                for (ExtSSuppliersInspectionTmpl extSSuppliersInspectionTmpl : list) {
                    ExtSSuppliersInspectionItems extSSuppliersInspectionItems1 = new ExtSSuppliersInspectionItems();
                    BeanUtils.copyProperties(extSSuppliersInspectionTmpl, extSSuppliersInspectionItems1);
                    extSSuppliersInspectionItems1.setChilds(ListObjCopyUtil.copyTo(extSSuppliersInspectionTmpl.getChilds(), SSuppliersInspectionItems.class));
                    extSSuppliersInspectionItems.add(extSSuppliersInspectionItems1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        suppliersInspectionDetailVO.setExtSSuppliersInspectionItems(extSSuppliersInspectionItems);

        LicenseUtil.INSTANCE.validate();
        return suppliersInspectionDetailVO;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void submitSupplierInspectionDetail(SuppliersInspectionDetailVO vo) {
        SSuppliersInspection sSuppliersInspection = vo.getSSuppliersInspection();
        String userId = UserUtils.getCurrentUserId();
        sSuppliersInspectionService.updateById(sSuppliersInspection);
        SSuppliersInspectionAc sSuppliersInspectionAc = vo.getSSuppliersInspectionAc();
        List<ExtSSuppliersInspectionItems> extSSuppliersInspectionItems = vo.getExtSSuppliersInspectionItems();
        if (sSuppliersInspectionAcService.selectByInspectId(sSuppliersInspection.getId()) == null) {
            sSuppliersInspectionAc.setId(null);
            sSuppliersInspectionAc.setSuppliersInspectionId(sSuppliersInspection.getId());
            sSuppliersInspectionAc.setSuppliersId(sSuppliersInspection.getSuppliersId());
            sSuppliersInspectionAc.setBaseFeilds(userId, "", CommonConstants.DEL_FLAG_NORMAL, true);
            for (ExtSSuppliersInspectionItems extSSuppliersInspectionItem : extSSuppliersInspectionItems) {
                extSSuppliersInspectionItem.setId(null);
                extSSuppliersInspectionItem.setSuppliersId(sSuppliersInspection.getSuppliersId());
                extSSuppliersInspectionItem.setSuppliersInspectionId(sSuppliersInspection.getId());
                extSSuppliersInspectionItem.setBaseFeilds(userId, "", CommonConstants.DEL_FLAG_NORMAL, true);
                sSuppliersInspectionItemsService.insert(extSSuppliersInspectionItem);
                if (CollectionUtils.isNotEmpty(extSSuppliersInspectionItem.getChilds())) {
                    for (SSuppliersInspectionItems sSuppliersInspectionItems : extSSuppliersInspectionItem.getChilds()) {
                        sSuppliersInspectionItems.setId(null);
                        sSuppliersInspectionItems.setParentId(extSSuppliersInspectionItem.getId());
                        sSuppliersInspectionItems.setSuppliersId(sSuppliersInspection.getSuppliersId());
                        sSuppliersInspectionItems.setSuppliersInspectionId(sSuppliersInspection.getId());
                        sSuppliersInspectionItems.setBaseFeilds(userId, "", CommonConstants.DEL_FLAG_NORMAL, true);
                        sSuppliersInspectionItemsService.insert(sSuppliersInspectionItems);
                    }
                }
            }
        } else {
            for (ExtSSuppliersInspectionItems extSSuppliersInspectionItem : extSSuppliersInspectionItems) {
                if (CollectionUtils.isNotEmpty(extSSuppliersInspectionItem.getChilds())) {
                    for (SSuppliersInspectionItems sSuppliersInspectionItems : extSSuppliersInspectionItem.getChilds()) {
                        sSuppliersInspectionItemsService.updateById(sSuppliersInspectionItems);
                    }
                } else {
                    sSuppliersInspectionItemsService.updateById(extSSuppliersInspectionItem);
                }
            }
        }
        sSuppliersInspectionAcService.insertOrUpdate(sSuppliersInspectionAc);


        LicenseUtil.INSTANCE.validate();
        //清除之前的附件
        List<SAttachment> sAttachments = Lists.newArrayList();
        SAttachment where = new SAttachment();
        where.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
        where.setFormId(sSuppliersInspection.getId());
        EntityWrapper entityWrapper = new EntityWrapper(where);
        entityWrapper.in("attachment_type", "61,62,63,64,65,66,67");
        SAttachment update = new SAttachment();
        update.setDelFlag(CommonConstants.DEL_FLAG_DELETE);
        sAttachmentService.update(update, entityWrapper);
        if (vo.getSAttachments1() != null)
            sAttachments.addAll(vo.getSAttachments1());
        if (vo.getSAttachments2() != null)
            sAttachments.addAll(vo.getSAttachments2());
        if (vo.getSAttachments3() != null)
            sAttachments.addAll(vo.getSAttachments3());
        if (vo.getSAttachments4() != null)
            sAttachments.addAll(vo.getSAttachments4());
        if (vo.getSAttachments5() != null)
            sAttachments.addAll(vo.getSAttachments5());
        if (vo.getSAttachments6() != null)
            sAttachments.addAll(vo.getSAttachments6());
        if (vo.getSAttachments7() != null)
            sAttachments.addAll(vo.getSAttachments7());
        for (SAttachment sAttachment : sAttachments) {
            sAttachment.setId(null);
            sAttachment.setFormId(sSuppliersInspection.getId());
            sAttachment.setBaseFeilds(userId, "", CommonConstants.DEL_FLAG_NORMAL, true);
            sAttachmentService.insert(sAttachment);
        }
    }

    @Override
    public List<TeamMembersOpinionVO> getTeamMembersOpinionInfos(String rcRelatedId) {
        List<TeamMembersOpinionVO> teamMembersOpinionInfo = this.getTeamMembersOpinionInfo(rcRelatedId);
        if (teamMembersOpinionInfo != null && teamMembersOpinionInfo.size() > 0) {
            for (TeamMembersOpinionVO obj : teamMembersOpinionInfo) {
                String userName = sysUserService.getSysUserNameByIds(obj.getCreateBy());
                if (StringUtils.isNotEmpty(userName)) obj.setCreateByUserName(userName);
            }
        }
        return teamMembersOpinionInfo;
    }

    @Override
    public boolean isCompleteReport(String inspectId) {
        return sSuppliersInspectionAcService.selectByInspectId(inspectId) != null;
    }
}
